Welcome Folks I am back with another blog post. In this blog post I will be introducing to you a nice Node.js Library called as Async. With the help of this library you can handle Asynchronous tasks in your application very easily. This library is particularly useful in making real time application such as Facebook Messenger, Single Page Web Applications etc.

What is Async?

Async is a utility module in node which provides straight-forward, powerful functions for working with asynchronous JavaScript

Installation

Although originally designed for use with Node.js and installable via

npm install async

it can also be used directly in the browser. A ESM version is included in the main async package that should automatically be used with compatible bundlers such as Webpack and Rollup.

A pure ESM version of Async is available as async-es .

Usage

The usage of this library is pretty simple. First of all import the library by using the require function and passing the library name i.e. async and then you can use it later. The source code is given below. This is a commonly used scenario where you are using callbacks to request data. Here in this case we are requesting json file.

// for use with Node-style callbacks... var async = require("async"); var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; var configs = {}; async.forEachOf(obj, (value, key, callback) => { fs.readFile(__dirname + value, "utf8", (err, data) => { if (err) return callback(err); try { configs[key] = JSON.parse(data); } catch (e) { return callback(e); } callback(); }); }, err => { if (err) console.error(err.message); // configs is now a map of JSON data doSomethingWith(configs); });

Usage with Fetch API

You can also use this library with Fetch API. Just request the data using the fetch syntax as shown below.

var async = require("async"); // ...or ES2017 async functions async.mapLimit(urls, 5, async function(url) { const response = await fetch(url) return response.body }, (err, results) => { if (err) throw err // results is now an array of the response bodies console.log(results) })

Async Library Total Methods

This library provides you a total of 70 methods that you can use which include the most popular ones such as

map reduce filter each

All these functions assume you follow the Node.js convention of providing a single callback as the last argument of your asynchronous function — a callback which expects an Error as its first argument — and calling the callback once.

Quick Examples

async.map(['file1','file2','file3'], fs.stat, function(err, results) { // results is now an array of stats for each file }); async.filter(['file1','file2','file3'], function(filePath, callback) { fs.access(filePath, function(err) { callback(null, !err) }); }, function(err, results) { // results now equals an array of the existing files }); async.parallel([ function(callback) { ... }, function(callback) { ... } ], function(err, results) { // optional callback }); async.series([ function(callback) { ... }, function(callback) { ... } ]);

Multiple callbacks

It is always advisable to throw a return callback(err, result) whenever the callback call is not a last line of the function. Always avoid multiple callbacks.

async.waterfall([ function(callback) { getSomething(options, function (err, result) { if (err) { callback(new Error("failed getting something:" + err.message)); // we should return here } // since we did not return, this callback still will be called and // `processData` will be called twice callback(null, result); }); }, processData ], done)

Using ES2017 async functions

async.mapLimit(files, 10, async file => { // <- no callback! const text = await util.promisify(fs.readFile)(dir + file, 'utf8') const body = JSON.parse(text) // <- a parse error here will be caught automatically if (!(await checkValidity(body))) { throw new Error(`${file} has invalid contents`) // <- this error will also be caught } return body // <- return a value! }, (err, contents) => { if (err) throw err console.log(contents) })

Download

The source is available for download from GitHub. Alternatively, you can install using npm:

$ npm install async

As well as using Bower:

$ bower install async

You can then require() async as normal:

var async = require ( "async" );

Or require individual methods:

var waterfall = require("async/waterfall"); var map = require("async/map");

In the Browser

Async should work in any ES2015 environment (Node 6+ and all modern browsers).

If you want to use Async in an older environment, (e.g. Node 4, IE11) you will have to transpile.

Usage

<script type="text/javascript" src="async.js"></script> <script type="text/javascript"> async.map(data, asyncProcess, function(err, results) { alert(results); }); </script>