如何以干净的方式等待多个事件的发出?

就像是:

event.on(['db:mongo:ready', 'db:redis:ready', 'db:rethinkdb:ready'], function() {
   server.listen()
});

最佳答案

只需使用 Promise.all 等待所有事件准备就绪。

示例使用 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
});

关于Node.js 等待多个事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26275099/

10-16 14:32