Skip to content

Instantly share code, notes, and snippets.

@mdang
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save mdang/97211053794de8a8cf48 to your computer and use it in GitHub Desktop.

Select an option

Save mdang/97211053794de8a8cf48 to your computer and use it in GitHub Desktop.
Asynchronous Control Flow with Node.js

Asynchronous Control Flow with Node.js

Differences b/w asynchronous and synchronous code in Node.js

  • Recommended that you stick with aynchronous code whenever possible
  • Synchronous code is blocking for all users since it's single threaded process
  • Blocking code isn't that big of a deal with one user, but with additional users it becomes a huge problem
  • Requires a different way of thinking when it comes to your code

Demonstration

Synchronous

var data = fs.readFileSync('/etc/passwd');

Asynchronous

fs.readFile('/etc/passwd', function(err, data) {
  // ...
} );

Callbacks

Structure
function(err, data) {
  // ...
}
Callback Hell
Control Flow with async
async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
      // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment