Wednesday, May 18, 2011

async.js - asynchronous control flow in node.js and the browser

Wynn sat down with Nick Quaranto at Red Dirt Ruby Conference to talk about Gemcutter, RubyGems.org, and how to get started creating your own Ruby gem.

async.js, written by Caolan McMahon, is a fresh take on asynchronous control flow for node.js and the browser. It offers a simple API for executing some of the more difficult asynchronous control flow patterns which can cause even the most seasoned JavaScript developer to give up in an asynchronous rage.

async.js provides around 20 functions that include several async functional methods (map, reduce, filter, forEach, …) as well as common patterns for control flow (parallel, series, waterfall, whilst, queue, until, …). All these functions assume you follow the JavaScript convention of providing a single callback as the last argument of your async function.

Here is a simple example of using some of the basic asynchronous iterators. There are a lot more examples on the Github page.

var async = require('async'), fs = require('fs');var files = ['file1.txt', 'file2.txt', 'file3.txt'];var writeFile = function(file, callback) { console.log('Attempting to write file ' + file); fs.writeFile(file, 'foo', callback);};// Writes files in parallelasync.forEach(files, writeFile, function(err){ if (err) { console.log(err); return; } console.log('all operations complete without any errors');});// Writes files in seriesasync.forEachSeries(files, writeFile, function(err){ if (err) { console.log(err); return; } console.log('all operations complete without any errors');});

This is a contrived example, but it is paramount to understanding the power of the async.js library. Without the async.js library or a similar control flow library, you might get stuck writing brittle code with lots of nested callbacks.

No comments:

Post a Comment