Put on Your Asynchronous Hat and Node
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Put on Your Asynchronous Hat and Node

on

  • 2,410 views

Introduction in asynchronous programming in Node.js, async.js, and q promises.

Introduction in asynchronous programming in Node.js, async.js, and q promises.

Statistics

Views

Total Views
2,410
Views on SlideShare
1,678
Embed Views
732

Actions

Likes
2
Downloads
13
Comments
1

13 Embeds 732

http://java.dzone.com 517
http://librosweb.es 100
http://blog.shinetech.com 53
http://architects.dzone.com 19
http://cloud.feedly.com 10
http://server.dzone.com 10
http://rss.com 8
http://css.dzone.com 5
https://twitter.com 3
http://www.dzone.com 3
http://www.linkedin.com 2
http://192.168.3.23 1
http://www.verious.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Put on Your Asynchronous Hat and Node Presentation Transcript

  • 1. #wdc13Put On Your AsynchronousHat and NodeMarc Fasel @marcfaselShine Technologies http://blog.shinetech.com1Saturday, 4 May 13
  • 2. #wdc13What is an Asynchronous Hat?2Saturday, 4 May 13
  • 3. #wdc13Node.jsServer-side JavaScript platformEvent-driven, non-blocking I/OAll I/O is asynchronousAsynchrononous everywhere3Saturday, 4 May 13
  • 4. #wdc13Different MindsetsSynchronous coding comes naturalNatural execution orderAsynchronous coding a bit harderSerial execution leads to nestingNew: parallel executionSingle Callback functions and Event EmittersExplicit error handling4Saturday, 4 May 13
  • 5. #wdc13Synchronous Codevar filenames = fs.readdirSync(/tmp/);for (var i = 0; i < filenames.length; i++) {console.log(filenames[i]);}console.log(Done.);5Saturday, 4 May 13
  • 6. #wdc13Asynchronous Codefs.readdir(/tmp/, function (err, filenames) {for (var i = 0; i < filenames.length; i++) {console.log(filenames[i]);}console.log(Done.);});6Saturday, 4 May 13
  • 7. #wdc13Some More Synchronous Codevar totalBytes = 0;for (var i = 0; i < filenames.length; i ++) {var stats = fs.statSync(/tmp/ + filenames[i]);totalBytes += stats.size;}console.log(Total bytes: + totalBytes);7Saturday, 4 May 13
  • 8. #wdc13Asynchronous Parallel Executionvar count = filenames.length;for (var i = 0; i < filenames.length; i++) {! fs.stat(/tmp/ + filenames[i], function (err, stats) {! ! totalBytes += stats.size;! ! count--;! ! if (count === 0) {! ! ! // We’re done! ! ! console.log(Total bytes: + totalBytes);! ! }! });};8Saturday, 4 May 13
  • 9. #wdc13fs.readFile(dirFrom+filename,utf-8, function (err, data){! ! if (err) return callback(err);! ! fs.writeFile(dirTo+filename,data,utf-8, function (err){! ! ! ! if (err) return callback(err);! ! ! ! fs.chmod(dirTo+filename,0777, function (err){! ! ! ! ! ! if (err) return callback(err);! ! ! ! ! ! anotherAsyncFunction(param1, function (err){! ! ! ! ! ! ! ! if (err) return callback(err);! ! ! ! ! ! ! ! anotherAsyncFunction(param1, function (err){! ! ! ! ! ! ! ! })! ! ! ! ! ! })! ! ! ! })! ! })});Pyramid of Doom9Saturday, 4 May 13
  • 10. #wdc13Event MechanismsEvents used for asynchronous communicationTwo types of asynchronous functions:Single Callback:  one ‘done’ event, single callback functionEvent Emitter:  more than one event10Saturday, 4 May 13
  • 11. #wdc13Single Callback Functionsfs.readdir(dir, function (err, filenames) {// Failure! if (err) return callback(err);// Success! console.log(dir + has + filenames.length + files.);});!11Saturday, 4 May 13
  • 12. #wdc13Event Emittervar readStream = fs.createReadStream(filename);readStream.on(open, function () {! readStream.pipe(res);});readStream.on(error, function(err) {! // Failure! res.end(err);});12Saturday, 4 May 13
  • 13. #wdc13Error HandlingSynchronousExceptions give us lots of goodiesAsynchronousExplicit error code everywhereLots of boilerplateMore Pyramid of Doom13Saturday, 4 May 13
  • 14. #wdc13Synchronous Error HandlingWe are blessed with ExceptionsStop execution immediatelyAutomatically bubble up call hierarchyError code logically separated from application code14Saturday, 4 May 13
  • 15. #wdc13World With Exceptionsfunction readFile(fileName) {! var file = openFile(fileName);! var data = readContent(file);! closeFile(file);! return data;}function readContent(file) {! throw new Error("Exception!");}try {! var myData = readFile(fileName);} catch (e) {! // Handle error!}15Saturday, 4 May 13
  • 16. #wdc13World Before Exceptionsfunction readFile(err, filePath) {! var file = openFile(err, filePath);! if (err) { return err; }! var data = readContent(err, file);! if (err) { return err;}! closeFile(err, file);! if (err) { return err; }! return data;}var myFileContent = readFile(err,filePath);if (err) { // Handle error };16Saturday, 4 May 13
  • 17. #wdc13Asynchronous Error Handlingtry {fs.readFile(/tmp/test.txt, utf-8, function (err, data) {!if (err) {!! throw err;!}console.log(data);});!} catch (e) {! console.log(e);}Exceptions possibletry/catch does not have desired result17Saturday, 4 May 13
  • 18. #wdc13Callback Error Handlingfs.readFile(/tmp/test.txt, utf-8, function (err, data) {! if (err) return callback(err);! // Success! console.log(data);});!18Saturday, 4 May 13
  • 19. #wdc13Event Emitter Error Handlingvar readStream = fs.createReadStream(filename);readStream.on(open, function () {! readStream.pipe(res);});readStream.on(error, function(err) {res.end(err);});19Saturday, 4 May 13
  • 20. #wdc13Pyramid of Doom With Error Handlingfs.readFile(dirFrom+filename,utf-8, function (err, data){! ! if (err) return callback(err);! ! fs.writeFile(dirTo+filename,data,utf-8, function (err){! ! ! ! if (err) return callback(err);! ! ! ! fs.chmod(dirTo+filename,0777, function (err){! ! ! ! ! ! if (err) return callback(err);! ! ! ! ! ! anotherAsyncFunction(param1, function (err){! ! ! ! ! ! ! ! if (err) return callback(err);! ! ! ! ! ! ! ! anotherAsyncFunction(param1, function (err){! ! ! ! ! ! ! ! ! if (err) return callback(err);! ! ! ! ! ! ! ! ! callback();! ! ! ! ! ! ! ! })! ! ! ! ! ! })! ! ! ! })! ! })});20Saturday, 4 May 13
  • 21. #wdc13Asynchronous Error HandlingCan’t catch exceptions that happen in callbacksExplicit code to handle errorSimple Callback: error code gets mixed with application codeEvent Emitter: error code separate21Saturday, 4 May 13
  • 22. #wdc13Help is Available22Saturday, 4 May 13
  • 23. #wdc13Named Callbacksfs.readdir(/tmp/, readDirCallback);function readDirCallback (err, filenames) {for (var i = 0; i < filenames.length; i++) {console.log(filenames[i]);}console.log(Done.);};23Saturday, 4 May 13
  • 24. #wdc13Nesting Named Callbacksfunction copyFile(filePathFrom, filePathTo, callback){! fs.readFile(filePathFrom,utf-8, readFileCallback);! function readFileCallback(err, data){! ! if (err) return callback(err);! ! fs.writeFile(filePathTo, data, utf-8, writeFileCallback);! ! function writeFileCallback(err){! ! ! if (err) return callback(err);! ! ! callback();! ! };! };};24Saturday, 4 May 13
  • 25. #wdc13Control Flow librariesFix problems with asynchronous Control FlowControl flow first thing people want to fixMany control flow libraries available25Saturday, 4 May 13
  • 26. #wdc13Async.jsThe Underscore.js of asynchronous codeControl flow constructsFunctional constructs26Saturday, 4 May 13
  • 27. #wdc13Seriesasync.series([! function(callback) {! ! fs.chmod(file1,0777, function (err){! ! ! if (err) return callback(err);! ! ! callback ();! ! });! },! function(callback) {! ! fs.chmod(file2,0777, function (err){! ! ! if (err) return callback(err);! ! ! callback();! ! });! }],! function done(err) {! ! if (err) return console.log(err);! ! console.log (Done.);! });27Saturday, 4 May 13
  • 28. #wdc13Parallelasync.parallel([! function(callback) {! ! fs.chmod(file1,0777, function (err){! ! ! if (err) return callback(err);! ! ! callback ();! ! });! },! function(callback) {! ! fs.chmod(file2,0777, function (err){! ! ! if (err) return callback(err);! ! ! callback();! ! });! }],! function done(err) {! ! if (err) return console.log(err);! ! console.log (Done.);! });28Saturday, 4 May 13
  • 29. #wdc13Functional Constructsasync.map([file1,file2,file3], fs.stat, function(err, results){// results is now an array of stats for each file});async.filter([file1,file2,file3], path.exists, function(results){// results now equals an array of the existing files});async.reduce(...);29Saturday, 4 May 13
  • 30. #wdc13PromisesPattern for asynchronous control flowPromises are objects representing a future outcome of anasynchronous callOutcome will be either ‘resolved’ or ‘rejected’Attach callbacks to ‘resolved’, ‘rejected’30Saturday, 4 May 13
  • 31. #wdc13Callback -> Promisefunction getReadFilePromise(){! var deferred = q.defer();! fs.readFile(/tmp/test.txt, utf-8, function (err, data) {! ! if (err) { deferred.reject(err); }! ! deferred.resolve(data);! });! !! return deferred.promise;}31Saturday, 4 May 13
  • 32. #wdc13Promisesvar readFilePromise = getReadFilePromise();readFilePromise.then(function(data){ console.log(Resolved: + data); },function(err){ console.log(Rejected: + err); });32Saturday, 4 May 13
  • 33. #wdc13PromisesCool Stuff: Promise Chaining33Saturday, 4 May 13
  • 34. #wdc13Promise ChainingreadFilePromise(filePathFrom)! .then(writeFilePromise(filePathTo))! .then(changeFilePermissionPromise(filePathTo,777))! .then(oneMorePromise())! .then(oneMorePromise());var promises = [! readFilePromise,! writeFilePromise,! changeFilePermissionPromise,! oneMorePromise,! oneMorePromise];var allPromise = Q.all(promises);34Saturday, 4 May 13
  • 35. #wdc13Promise Error HandlingreadFilePromise(filePathFrom)! .then(writeFilePromise(filePathTo))! .then(changeFilePermissionPromise(filePathTo,777),! ! errorCallback);35Saturday, 4 May 13
  • 36. #wdc13PromisesPromises help with asynchronous control flowAvoid the Pyramid of DoomException style error bubbling36Saturday, 4 May 13
  • 37. #wdc13ConclusionAsynchronous programming needs an asynchronous hatNew thingsCallbacksEvent EmittersExplicit error handlingFor the more difficult stuffNamed callbacksAsync.jsPromises37Saturday, 4 May 13
  • 38. #wdc13Thank you.38Saturday, 4 May 13
  • 39. #wdc13ReferencesTrevor Burnham - Async JavaScript: Build More Responsive Apps withLess CodePedro Teixeira - Professional Node.js: Building Javascript-BasedScalable SoftwareYou’re Missing the Point of Promises - http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/Popular Control Flow Libraries - http://dailyjs.com/2011/11/14/popular-control-flow/39Saturday, 4 May 13