2017-08-10 31 views
0

我想觸發一個功能,當兩個child_process已經完成。我想下面使用的承諾,但它似乎觸發Promise.all的承諾得到解決如何知道當兩個子進程已解決的NodeJS

let excelParserChildOnePromise = new Promise((resolveChild, rejectChild) => { 
    let excelParserChildOne = fork(excelParserTool); 

    excelParserChildOne.send(`${tempFilePositionOne}`); 
    excelParserChildOne.on('message', (excelArray) => { 
     console.log('child one resolved') 
     resolveChild(excelArray); 
    }) 
}); 

let excelParserChildTwoPromise = new Promise((resolveChild, rejectChild) => { 
    let excelParserChildTwo = fork(excelParserTool); 

    excelParserChildTwo.send(`${tempFilePositionTwo}`); 
    excelParserChildTwo.on('message', (excelArray) => { 
     console.log('child two resolved') 
     resolveChild(excelArray) 
    }) 
}); 


childPromises.push([excelParserChildOnePromise, excelParserChildTwoPromise]); 

Promise.all(childPromises).then(() => { 
    console.log('inside promise all'); 
}) 

此打印出之前,以下

inside promise all 
child one resolved 
child two resolved 

我怎麼聽當這兩個過程完成?

回答

1

你的.push()進入數組是錯誤的,因爲你正在推送一個promise數組,它給你一個數組的數組而不僅僅是一個簡單的promise數組,然後Promise.all()獲取錯誤類型的數據(它只是看到一個數組數組),所以它不能正常等待的承諾:

要修復它,改變這一行:

childPromises.push([excelParserChildOnePromise, excelParserChildTwoPromise]); 

這樣:

childPromises.push(excelParserChildOnePromise, excelParserChildTwoPromise); 
+0

啊..花了我20分鐘反正實現 – forJ

+0

感謝... – forJ

相關問題