How to wait some asynchronous tasks complete in Node.js?

Sometimes, we want to wait some asynchronous tasks complete in Node.js.

In this article, we’ll look at how to wait some asynchronous tasks complete in Node.js.

How to wait some asynchronous tasks complete in Node.js?

To wait some asynchronous tasks complete in Node.js, we can use promises.

For instance, we write

const mongoose = require('mongoose');

mongoose.connect('...');
const conn = mongoose.connection;

const promises = ['aaa', 'bbb', 'ccc'].map((name) => {
  return new Promise((resolve, reject) => {
    const collection = conn.collection(name);
    collection.drop((err) => {
      if (err) {
        return reject(err);
      }
      console.log('dropped ' + name);
      resolve();
    });
  });
});

(async () => {
  await Promise.all(promises)
  // ...
})()

to call map on an array with a callback to map the array entries to promises.

We create the promise with the Promise constructor.

We call Promise with a callback that calls resolve when the async operation is done.

And then we call Promise.all with the array of promises to run all the promises.

await will make sure all the promises are done until the lines below it is run.

Conclusion

To wait some asynchronous tasks complete in Node.js, we can use promises.