例如,在 SIGINT 处理程序中,我需要等待所有子进程完成。但是子进程的“关闭”事件可能有处理程序,它们本身可能会执行异步操作,例如外部通知。
所以我需要等到
- child.close 和
- child.close 处理程序已完成并且
- 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
我正在尝试找到一种解决方案,使关闭处理程序尽可能简单。 我不知道如何命名这个案例,所以谷歌搜索没有帮助。
最佳答案
一种可能的解决方案是使用一些扩展的 EventEmitter
- 可以处理由事件监听器返回的 promise
- 为收集的 Promise 实现类似
Q.all()
的行为 - 在所有监听器完成时发出另一个事件(包括等待 Promise)
我会尝试在 npm 注册表中找到这样的内容,或者如果没有找到,我会自己实现一个。
关于javascript - 当所有异步处理程序完成时执行 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22731374/