Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js wait for multiple events

How to wait in a clean way for multiple events to be emitted ?

Something like:

event.on(['db:mongo:ready', 'db:redis:ready', 'db:rethinkdb:ready'], function() {
   server.listen()
});
like image 201
Unitech Avatar asked Oct 22 '25 05:10

Unitech


1 Answers

Just use Promise.all to wait for all events to be ready.

Example wait multiple connection with mongoose:

const mongoose1 = require("mongoose");
const mongoose2 = require("mongoose");

const dbUrl1 = "mongodb://localhost:27017/db1";
const dbUrl2 = "mongodb://localhost:27017/db2";

mongoose1.connect(dbUrl1);
mongoose2.connect(dbUrl2);

const allDb = [mongoose1, mongoose2];

function waitEvent(event) {
  return new Promise((resolve, reject) => {
    event.on("connected", resolve);
    event.on("error", reject);
  });
}

async function prepareAllDb() {
  let pendingProcess = [];

  allDb.forEach(database => {
    // mongoose put their event on mongoose.connection
    pendingProcess.push(waitEvent(database.connection));
  });

  await Promise.all(pendingProcess);
}

prepareAllDb().then(() => {
  console.log("All databases are ready to use");

  // Run your server in here
});
like image 72
Squidward Tentacles Avatar answered Oct 24 '25 19:10

Squidward Tentacles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!