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()
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With