Uni*_*ech 4 event-handling node.js dom-events
如何以干净的方式等待多个事件的发出?
就像是:
event.on(['db:mongo:ready', 'db:redis:ready', 'db:rethinkdb:ready'], function() {
server.listen()
});
Run Code Online (Sandbox Code Playgroud)
只需用于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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2259 次 |
| 最近记录: |