【问题标题】:Node.js wait for multiple eventsNode.js 等待多个事件
【发布时间】:2014-10-09 09:37:30
【问题描述】:

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

类似:

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

【问题讨论】:

  • 你研究过承诺吗?
  • 没有,但我可以 event.emit('something') 吗?
  • 是的,你可以。我的理解是您想知道所有事件何时被触发。

标签: node.js event-handling dom-events


【解决方案1】:

只需使用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
});

【讨论】:

    【解决方案2】:

    这个例子是使用rsvppromises 完成的:

    var RSVP = require('rsvp'),
        Promise = RSVP.Promise;
    
    var emitted_promises = [];
    
    
    yourEvents.foreach(function(eventName){
      emitted_promises.push(new Promise(function(resolve, reject){
        event.on(eventName, function(){
          resolve('done');
        });
      });
    });
    
    RSVP.all(emitted_promises)
      .then(function(emitted){
          //now you know they all are done
          emitted; //array of 'done' but can be passed anything you need
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 2011-07-21
      • 2012-09-13
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      相关资源
      最近更新 更多