我有并行线程,并希望在其中一个抛出错误时中断所有未完成的线程。但似乎所有其他线程都在继续执行。
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';
}我得到日志
0
Error
1
2
3
4
5
6
7
8
9因此,当第一次调用"worker“函数(使用i=0)时抛出错误时,它会被函数"test”中的"catch“块捕获。然后,向上面的函数抛出错误,但其他9个工作进程仍在继续工作。有什么方法可以打破它们吗?我只看到一种方法-在函数“process.exit”的catch "block“中调用测试,但它将中断所有程序,而不是当前函数。
发布于 2020-08-21 20:50:34
您应该使用Promise.race: Promise.race()方法返回一个promise,该promise在可迭代的promise中的某个promise实现或拒绝时立即实现或拒绝,并返回该promise的值或原因。
请参阅更多https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race。
https://stackoverflow.com/questions/63523219
复制相似问题