2014-03-29 72 views
1

例如,在SIGINT處理程序中,我需要等到所有子進程完成。但是可能有處理兒童「關閉」事件的問題,它們本身可能會執行異步操作,如外部通知。所有異步處理程序完成後執行javascript函數

所以我需要等到

  1. child.closed和
  2. 完成child.closed處理程序和處理程序child.closed發起
  3. 異步操作都完成。

以下簡化的當前代碼只知道第二個檢查點。

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

我正試圖找到一種解決方案,它可以使close-handlers儘可能簡單。 我不知道如何命名這個案例,所以使用谷歌搜索沒有幫助。

回答

0

一個可能的解決方案是使用一些擴展EventEmitter這

  1. 可以處理的承諾,通過事件偵聽器返回
  2. 實現對收集的承諾
  3. 發出的所有listeners-另一個事件Q.all()般的行爲完成(包括等待承諾)

我會嘗試在npm註冊表中找到這樣的內容,或者如果找不到任何內容,我將自己實現一個。

相關問題