user5956451
user5956451

Reputation:

Node.js: How to do something when all my Worker threads have finished?

I have a small Node.js program that calculates two Fibonacci numbers concurrently. When both numbers have been calculated the program prints Finished. I am doing this by implementing on('exit', ...) where my callback decreases a counter and prints Finished if it reaches 0. My question is: Is there something more elegant, something like waitAll()?

Here is the program:

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)}`);
}

Upvotes: 1

Views: 738

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

If you promisify the event handler, you can use Promise.all:

 const done = el => new Promise(res => el.on("exit", res));

 Promise.all([
  done(w1),
  done(w2)
]).then(/*...*/)

Upvotes: 1

Related Questions