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

标签 javascript node.js events asynchronous

例如,在 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

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

最佳答案

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

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

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

关于javascript - 当所有异步处理程序完成时执行 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22731374/

相关文章:

java - AWS Transcribe - 当我们看到 "IsPartial"标志设置为 False 时如何停止转录

javascript - 有没有办法在 iframe 中注入(inject) javascript 代码来执行而不删除并重新附加包含它的脚本标签?

javascript - 正则表达式检查输入是否只是整数 (int) ,并检查另一个是否只是带有 2 个小数位的数字

javascript - 我可以将 javascript 模块与 "regular"javascript 混合使用吗?

javascript - 在另一个文件中访问 MySQL 的输出

javascript - 如何将名称添加到未命名的 JSON 对象数组中?

c# - 在异步处理程序中最初将 handled 属性设置为 true 后,如何重新传播事件?

javascript - 在 iPhone 上,Vimeo Javascript API .play() 函数在播放视频之前不起作用

node.js - 在 fs.opendir() 创建的 fs.Dir 上的异步迭代器之后 dir.close() 出错

javascript - 使用 DOM javascript 设置事件