The Async Library

Learn about the Async library and its provided features and patterns.

We'll cover the following

If we take a look for a moment at every control flow pattern we’ve analyzed so far, we’ll see that they can be used as a base to build reusable and more generic solutions. For example, we can wrap the unlimited parallel execution algorithm into a function that accepts a list of tasks, runs them in parallel, and invokes the given callback when all of them are complete. This way of wrapping control flow algorithms into reusable functions can lead to a more declarative and expressive way of defining asynchronous control flows, and that’s exactly what the Async library does.

The async library (not to be confused with the async/await keywords) is a very popular solution, in Node.js and JavaScript in general, for dealing with asynchronous code. It offers a set of functions that greatly simplify the execution of tasks in different configurations, and it also provides useful helpers for dealing with collections asynchronously. Even though there are several other libraries with a similar goal, async is the de facto standard in Node.js due to its historic popularity, especially when using callbacks to define asynchronous tasks.

To get an idea of some of the most important capabilities of the Async module, here’s a sample of the functionalities it exposes:

Features of the async library

  • Execute asynchronous functions over a collection of elements (in series or in parallel with limited concurrency).

  • Execute a chain of asynchronous functions (waterfall) where the output of every function becomes the input of the next one.

  • Offers a queue abstraction functionally equivalent to the one we implemented with our TaskQueue utility.

  • Provides other interesting asynchronous patterns such as race (executes multiple asynchronous functions in parallel and stops when the first one completes).

Once we’ve understood the fundamentals of the asynchronous patterns described in this chapter, we shouldn’t rely on the simplified implementations presented here for our everyday control flow needs. Instead, it’s better to adopt a broadly used and rigorously tested library like async for our production applications, unless our use case is so advanced that we require a custom algorithm.

Get hands-on with 1400+ tech skills courses.