Colin
Colin

Reputation: 1855

Working with async in node.js

I'm a little confused to as how to properly use the async module. Say I have:

result = long_sync_io_function();
short_sync_function(result);
... //other stuff dependent on result

Generally, in Node you convert long_sync_io_function() to its asynchronous counterpart long_async_io_function(callback(err, result)) and do something like:

long_async_io_function(function(err, result) {
    if (!err) {
         short_sync_function(result);
         ...//other stuff dependent on result
    }
});

But the constant embedding of callbacks quickly means lots and lots of indentation. Is the correct way to use async:

//1
async.waterfall([
    function(callback) {
        result = long_sync_io_function();
        callback(null, result);
    },
    function(result, callback) {
        short_sync_function(result);
        //other stuff dependent on result
    }
]);

or

//2
async.waterfall([
    function(callback) {
        long_async_io_function(callback);
    },
    function(result, callback) {
        short_sync_function(result);
        ...//other stuff dependent on result
    }
]);

Are these equivalent? I can't tell if aysnc helps create asynchronous code as in 1, or just aids in structuring existing asynchronous code as in 2.

Upvotes: 0

Views: 140

Answers (1)

slebetman
slebetman

Reputation: 114014

The async library has no ability to create asynchronous functions/code. Instead it is meant as helpers for higher order structure/organisation of code that's already asynchronous.

So it's number 2.


Additional answer

For simply avoiding nesting callbacks you don't need to use the async library. Simply name your functions instead of declaring them inline. So, instead of:

long_async_io_function(function(err, result) {
    if (!err) {
         //..do stuff dependent on result
         another_async_function(function(err,result) {
            //..do other stuff
         });
    }
});

You can write it like this:

function do_other_stuff (err, result) {
    //..
}

function do_stuff_with_io_result (err, result) {
    //..
    another_async_function(do_other_stuff);
}

long_async_io_function(do_stuff_with_io_result );

This makes the code self documenting and much easier to debug (especially if you're stepping through in a debugger or looking at a stack trace) and you can therefore remove the redundant comments like do stuff with result and do other stuff.

Upvotes: 2

Related Questions