我有一个小的Node.js程序,可以同时计算两个斐波那契数。计算完两个数字后,程序将打印完成。我是通过实现on('exit', ...)
来实现的,在该回调中,我的回调将减少一个计数器,并在达到0时显示 Finished 。我的问题是:是否有更优雅的东西,例如waitAll()
?
这是程序:
const { Worker, isMainThread, workerData } = require('worker_threads');
function fibonacci(n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) +
fibonacci(n - 2);
}
}
let counter = 2;
if (isMainThread) {
let func = (code) => {
if (--counter === 0) {
console.log("Finished");
}
};
let w1 = new Worker(__filename, {workerData: 40});
w1.on('exit', func);
console.log("1");
let w2 = new Worker(__filename, {workerData: 45});
w2.on('exit', func);
console.log("2");
} else {
console.log(`Calculate fib(${workerData})`);
console.log(`fib(${workerData}) = ${fibonacci(workerData)}`);
}
答案 0 :(得分:2)
如果您承诺事件处理程序,则可以使用Promise.all:
const done = el => new Promise(res => el.on("exit", res));
Promise.all([
done(w1),
done(w2)
]).then(/*...*/)