Introducing the async module

As JavaScript is asynchronous by its very nature, there will undoubtedly come a time when we will need a way to handle executing a number of different asynchronous functions at the same time. The big issue here is that if we try to perform three different queries on a MongoDB server, for example, how will we know when all three are finished before we move on and do work with the results? Up until this point, we've simply been relying on a single callback function, which works great for a single call. How can we assign a single callback function to multiple asynchronous calls?

The answer is, we can not directly anyway. You can use a lot of nested callbacks to achieve this, but that is generally considered bad practice and will significantly reduce the readability of your code. You can use a third-party module, however, that was designed very specifically for this exact need. async is a powerful node module that can be downloaded and installed via npm and which provides a number of extremely useful utility functions, all designed to help when working with a series of asynchronous functions. Two functions that we are going to work with in this chapter are series and parallel. The series function allows us to execute asynchronous functions sequentially, each waiting until the previous function finishes before executing a single callback function at the end. The parallel function allows us to do the opposite--execute a number of asynchronous functions simultaneously, waiting until they are all complete, then executing a single callback function when the last function is finished.

How does a single callback function handle the responses of a number of different asynchronous functions, you ask? The answer is:

by accepting an array of the responses of each function as a parameter!

Since we are going to use async for our project, let's install it via npm and make sure our package.json file is updated as well. Within the root of your project folder, execute the following from the command line:

    $ npm install --save async
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.31.165