【问题标题】:Executing javascript function when all async-handlers completed当所有异步处理程序完成时执行 javascript 函数
【发布时间】:2014-03-29 12:56:32
【问题描述】:

例如,在 SIGINT 处理程序中,我需要等到所有子进程都完成。但是孩子的“关闭”事件可能有处理程序,它们本身可能执行异步操作,如外部通知。

所以我需要等到

  1. child.close 和
  2. child.close 处理程序已完成并且
  3. 在 child.close 处理程序中启动的异步操作已全部完成。

下面是简化的当前代码,它只知道第二个检查点。

var child_process = require('child_process');
var events = require('events');
var timers = require('timers');

var childRunning = false;   // has child flag (counter in actual app)

// starting child
var child = child_process.spawn(process.cwd()+'/stub.js',{detached:true});
childRunning = true;
child.on('close',function(){childRunning=false});   //

// example close handler with async action inside
// actually there is a bunch of such handlers
child.on('close',function(){
    console.log('child close handler triggered');
    timers.setTimeout(function(){
        console.log('close handler async action completed')
    }, 2000);
});

process.on('SIGINT',function(){
    console.log("Received SIGINT");
    closeApp=function(){
        console.log("readyToExit");
        process.exit();
    }
    if (!childRunning) closeApp();
    // in fact, i need here not this event, but 
    //   'all close handlers are done their job'
    child.once('close',closeApp);
})
// actually there is a daemon app, so it does not stop by itself at all

在此示例中,通常您会看到“关闭处理程序异步操作已完成”消息,但如果您按 ctrl+c 则该消息将丢失。所以我需要以某种方式将其重写为 se

我正在尝试找到一种解决方案,使近距离处理程序尽可能简单。 我不知道如何命名这个案例,所以谷歌搜索没有帮助。

【问题讨论】:

    标签: javascript node.js events asynchronous


    【解决方案1】:

    一种可能的解决方案是使用一些扩展的 EventEmitter

    1. 可以处理由事件监听器返回的承诺
    2. 为收集的 Promise 实现类似 Q.all() 的行为
    3. 在所有侦听器完成时发出另一个事件(包括等待承诺)

    我会尝试在 npm 注册表中找到这样的,或者如果没有找到,我会自己实现一个。

    【讨论】:

      猜你喜欢
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多