gpt4 book ai didi

Node.js 等待多个事件

转载 作者:搜寻专家 更新时间:2023-10-31 23:48:21 25 4
gpt4 key购买 nike

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

类似于:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com