02 Aug 2010

Async.js update and console utils

Since my last post on the async module its gained quite a few features, not least of which the ability to use it in the browser! However, one of the simplest additions is an async-friendly version of console.log and console.dir. Both of which are saving me quite a bit of typing when playing around in the node REPL.

But before demonstrating these functions, a quick overview of the latest features:

Same as reduce, but the iterator is applied in reverse order.
The opposite of filter, removes items that passes an async test.
Returns the first value is a list that passes an async truth test.
Sorts a list by the results of running each value through an async iterator, leaving the original values intact.
Calls the callback on a later loop around the event loop.
Creates a continuation with some arguments already applied, a useful shorthand when combined with other flow control functions.
Logs the result of an async function to the console.
Logs the result of an async function to the console using console.dir
Changes the value of async back to its original value, returning a reference to the async object.

Async.js now supports all the functions available as part of the excellent underscore.js library, provided they accept an iterator as one of their arguments. The only difference being that these iterators allow asynchronous execution using a callback. As I mentioned earlier, I'm already finding log and dir indispensable when playing with code in the node REPL. A read-eval-print-loop isn't especially well suited to asynchronous code. Consider the following function:

function hello(name, callback){
        callback(null, 'hello ' + name);
    }, 100);

To output the result of calling hello with 'world', you would need to enter the following into the REPL:

node> hello('world', function(err, result){
...     err ? console.error(err): console.log(result);
...   });
'hello world'

However, using async.log, this is reduced to:

node> async.log(hello, 'world');
'hello world'

I can't believe I managed so long without this! To install the async module, you can get the code from github, or install via npm:

npm install async