3

I have parallel threads, and want to interrupt all unfinished thread when one of them throws an error. But it seems that all other threads are continue to execute.

async test() {
    let threads = [];
    console.log('Starting threads');
    try {
        for (let i = 0; i < 10; i++) {
            threads.push(this.worker(i));
        }
        console.log(`Waiting for threads`);
        await Promise.all(threads);
    }
    catch (err) {
        console.log(err);
        throw err;
    }
}

async worker(i) {
    // Sleep for 2 seconds to emulate API request
    let p = new Promise((resolve, reject) => {
        return setTimeout(
            () => resolve(true),
            2000
        );
    }
    );
    await p;
    console.log(i);
    throw 'Error';
}

I get log

0
Error
1
2
3
4
5
6
7
8
9

So, when throws an error at the first call of the "worker" function (with i=0), it's catched by "catch" block in the function "test". Then and error is throwed to the upper function, but other 9 workers still continue to work. Is any way to break them? I see only one way - invoke process.exit in catch "block" in the function "test", but it will interrupt all program instead of the current function.

1 Answers1

2

You should use Promise.race: The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.

See more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race.

pacocom
  • 170
  • 1
  • 6