Working with Asynchronous Javascript in Node.js Using Async.js

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

 

 

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.

 

 

Usage with Fetch API

 

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

 

 

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

  1. map
  2. reduce
  3. filter
  4. 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

 

 

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.

 

 

Using ES2017 async functions

 

 

Download

 

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

 

 

As well as using Bower:

 

 

You can then require() async as normal:

 

 

Or require individual methods:

 

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

 

 

Other Libraries

  • limiter a package for rate-limiting based on requests per sec/hour.
  • neo-async an altername implementation of Async, focusing on speed.
  • co-async a library inspired by Async for use with co and generator functions.
  • promise-async a version of Async where all the methods are Promisified.

Leave a Reply