当所有异步处理程序完成时执行javascript函数

Executing javascript function when all async-handlers completed

本文关键字:完成时 执行 javascript 函数 程序 处理 异步      更新时间:2023-09-26

例如,在SIGINT处理程序中,我需要等待所有子进程完成。但是在子进程的'close'事件上可能有处理程序,这些处理程序本身可能执行异步操作,如外部通知。

所以我需要等到

  1. 孩子。关闭和
  2. 孩子。关闭处理程序完成,
  3. 在child中启动异步操作。关闭的处理程序全部完成。

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

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

在这个例子中,通常你会看到"close handler async action completed"消息,但是如果你按ctrl+c,那么这个消息将会错过。所以我需要把它重写为se

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

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

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

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