How to avoid deep nesting of asynchronous functions in Node.js?

Sometimes, we want to avoid deep nesting of asynchronous functions in Node.js.

In this article, we’ll look at how to avoid deep nesting of asynchronous functions in Node.js.

How to avoid deep nesting of asynchronous functions in Node.js?

To avoid deep nesting of asynchronous functions in Node.js, we can use the async.waterfall method.

We install the async package with

npm i async

Then we can use it by writing

const async = require("async");


async.waterfall([
  (callback) => {
    callback(null, 'one', 'two');
  },
  (arg1, arg2, callback) => {
    callback(null, 'three');
  },
  (arg1, callback) => {
    // arg1 now equals 'three'
    callback(null, 'done');
  }
], (err, result) => {
  // result now equals 'done'    
});

to call async.waterfall with an array of callback functions.

In each function, we call callback with the arguments we want so async.waterfall will proceed to calling the next callback in the array.

And when all the callbacks are called or if there’s an error, the callback in the 2nd argument is called.

Conclusion

To avoid deep nesting of asynchronous functions in Node.js, we can use the async.waterfall method.