Asynchronous parallel requests using Node.js

Async Library:

1What is Async

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.[Async]

2Installation using npm

npm install --save async

Usage in node.js:

1Documentation

Async function 2 parameters:

  • First argument: an array of the asynchronous functions
  • Second argument: a callback function that take two parameters an error object and an array of responses

2Code

exports.myFunction = (req, res, next) => {
  async.parallel(
    [
      function (callback) {
        // Category find using mongoose
        Category.findOne(callback)
      },
      function (callback) {
        // Article find using mongoose
        Article.findOne(
          {
            name: req.params.id
          },
          callback
        )
      }
    ],
    //callback execution
    function (err, result) {
      //handling errors
      if (err) {
        return res.status(500).json({
          message: err
        })
      }

      // returning response
      return res.status(200).json({
        categories: result[0],
        articles: result[1]
      })
    }
  )
}