#wdc13Put On Your AsynchronousHat and NodeMarc Fasel @marcfaselShine Technologies http://blog.shinetech.com1Saturday, 4 Ma...
#wdc13What is an Asynchronous Hat?2Saturday, 4 May 13
#wdc13Node.jsServer-side JavaScript platformEvent-driven, non-blocking I/OAll I/O is asynchronousAsynchrononous everywhere...
#wdc13Different MindsetsSynchronous coding comes naturalNatural execution orderAsynchronous coding a bit harderSerial exec...
#wdc13Synchronous Codevar filenames = fs.readdirSync(/tmp/);for (var i = 0; i < filenames.length; i++) {console.log(filena...
#wdc13Asynchronous Codefs.readdir(/tmp/, function (err, filenames) {for (var i = 0; i < filenames.length; i++) {console.lo...
#wdc13Some More Synchronous Codevar totalBytes = 0;for (var i = 0; i < filenames.length; i ++) {var stats = fs.statSync(/t...
#wdc13Asynchronous Parallel Executionvar count = filenames.length;for (var i = 0; i < filenames.length; i++) {! fs.stat(/t...
#wdc13fs.readFile(dirFrom+filename,utf-8, function (err, data){! ! if (err) return callback(err);! ! fs.writeFile(dirTo+fi...
#wdc13Event MechanismsEvents used for asynchronous communicationTwo types of asynchronous functions:Single Callback:  one ...
#wdc13Single Callback Functionsfs.readdir(dir, function (err, filenames) {// Failure! if (err) return callback(err);// Suc...
#wdc13Event Emittervar readStream = fs.createReadStream(filename);readStream.on(open, function () {! readStream.pipe(res);...
#wdc13Error HandlingSynchronousExceptions give us lots of goodiesAsynchronousExplicit error code everywhereLots of boilerp...
#wdc13Synchronous Error HandlingWe are blessed with ExceptionsStop execution immediatelyAutomatically bubble up call hiera...
#wdc13World With Exceptionsfunction readFile(fileName) {! var file = openFile(fileName);! var data = readContent(file);! c...
#wdc13World Before Exceptionsfunction readFile(err, filePath) {! var file = openFile(err, filePath);! if (err) { return er...
#wdc13Asynchronous Error Handlingtry {fs.readFile(/tmp/test.txt, utf-8, function (err, data) {!if (err) {!! throw err;!}co...
#wdc13Callback Error Handlingfs.readFile(/tmp/test.txt, utf-8, function (err, data) {! if (err) return callback(err);! // ...
#wdc13Event Emitter Error Handlingvar readStream = fs.createReadStream(filename);readStream.on(open, function () {! readSt...
#wdc13Pyramid of Doom With Error Handlingfs.readFile(dirFrom+filename,utf-8, function (err, data){! ! if (err) return call...
#wdc13Asynchronous Error HandlingCan’t catch exceptions that happen in callbacksExplicit code to handle errorSimple Callba...
#wdc13Help is Available22Saturday, 4 May 13
#wdc13Named Callbacksfs.readdir(/tmp/, readDirCallback);function readDirCallback (err, filenames) {for (var i = 0; i < fil...
#wdc13Nesting Named Callbacksfunction copyFile(filePathFrom, filePathTo, callback){! fs.readFile(filePathFrom,utf-8, readF...
#wdc13Control Flow librariesFix problems with asynchronous Control FlowControl flow first thing people want to fixMany contro...
#wdc13Async.jsThe Underscore.js of asynchronous codeControl flow constructsFunctional constructs26Saturday, 4 May 13
#wdc13Seriesasync.series([! function(callback) {! ! fs.chmod(file1,0777, function (err){! ! ! if (err) return callback(err...
#wdc13Parallelasync.parallel([! function(callback) {! ! fs.chmod(file1,0777, function (err){! ! ! if (err) return callback...
#wdc13Functional Constructsasync.map([file1,file2,file3], fs.stat, function(err, results){// results is now an array of st...
#wdc13PromisesPattern for asynchronous control flowPromises are objects representing a future outcome of anasynchronous cal...
#wdc13Callback -> Promisefunction getReadFilePromise(){! var deferred = q.defer();! fs.readFile(/tmp/test.txt, utf-8, func...
#wdc13Promisesvar readFilePromise = getReadFilePromise();readFilePromise.then(function(data){ console.log(Resolved: + data...
#wdc13PromisesCool Stuff: Promise Chaining33Saturday, 4 May 13
#wdc13Promise ChainingreadFilePromise(filePathFrom)! .then(writeFilePromise(filePathTo))! .then(changeFilePermissionPromis...
#wdc13Promise Error HandlingreadFilePromise(filePathFrom)! .then(writeFilePromise(filePathTo))! .then(changeFilePermission...
#wdc13PromisesPromises help with asynchronous control flowAvoid the Pyramid of DoomException style error bubbling36Saturday...
#wdc13ConclusionAsynchronous programming needs an asynchronous hatNew thingsCallbacksEvent EmittersExplicit error handling...
#wdc13Thank you.38Saturday, 4 May 13
#wdc13ReferencesTrevor Burnham - Async JavaScript: Build More Responsive Apps withLess CodePedro Teixeira - Professional N...
Upcoming SlideShare
Loading in …5
×

Put on Your Asynchronous Hat and Node

2,344
-1

Published on

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

Published in: Technology
1 Comment
2 Likes
Statistics
Notes
No Downloads
Views
Total Views
2,344
On Slideshare
0
From Embeds
0
Number of Embeds
14
Actions
Shares
0
Downloads
18
Comments
1
Likes
2
Embeds 0
No embeds

No notes for slide

Put on Your Asynchronous Hat and Node

  1. 1. #wdc13Put On Your AsynchronousHat and NodeMarc Fasel @marcfaselShine Technologies http://blog.shinetech.com1Saturday, 4 May 13
  2. 2. #wdc13What is an Asynchronous Hat?2Saturday, 4 May 13
  3. 3. #wdc13Node.jsServer-side JavaScript platformEvent-driven, non-blocking I/OAll I/O is asynchronousAsynchrononous everywhere3Saturday, 4 May 13
  4. 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. 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. 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. 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. 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. 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. 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. 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. 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. 13. #wdc13Error HandlingSynchronousExceptions give us lots of goodiesAsynchronousExplicit error code everywhereLots of boilerplateMore Pyramid of Doom13Saturday, 4 May 13
  14. 14. #wdc13Synchronous Error HandlingWe are blessed with ExceptionsStop execution immediatelyAutomatically bubble up call hierarchyError code logically separated from application code14Saturday, 4 May 13
  15. 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. 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. 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. 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. 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. 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. 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. 22. #wdc13Help is Available22Saturday, 4 May 13
  23. 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. 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. 25. #wdc13Control Flow librariesFix problems with asynchronous Control FlowControl flow first thing people want to fixMany control flow libraries available25Saturday, 4 May 13
  26. 26. #wdc13Async.jsThe Underscore.js of asynchronous codeControl flow constructsFunctional constructs26Saturday, 4 May 13
  27. 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. 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. 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. 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. 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. 32. #wdc13Promisesvar readFilePromise = getReadFilePromise();readFilePromise.then(function(data){ console.log(Resolved: + data); },function(err){ console.log(Rejected: + err); });32Saturday, 4 May 13
  33. 33. #wdc13PromisesCool Stuff: Promise Chaining33Saturday, 4 May 13
  34. 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. 35. #wdc13Promise Error HandlingreadFilePromise(filePathFrom)! .then(writeFilePromise(filePathTo))! .then(changeFilePermissionPromise(filePathTo,777),! ! errorCallback);35Saturday, 4 May 13
  36. 36. #wdc13PromisesPromises help with asynchronous control flowAvoid the Pyramid of DoomException style error bubbling36Saturday, 4 May 13
  37. 37. #wdc13ConclusionAsynchronous programming needs an asynchronous hatNew thingsCallbacksEvent EmittersExplicit error handlingFor the more difficult stuffNamed callbacksAsync.jsPromises37Saturday, 4 May 13
  38. 38. #wdc13Thank you.38Saturday, 4 May 13
  39. 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×