While all the questions about Promise.all
focus on how to wait for all promises, I want to go the other way -- when any of the promises fails, stop the others, or even stop the whole script.
Here's a short example to illustrate:
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'resolve1');
}).then(a => { console.log('then1'); return a; });
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 2000, 'reject2');
}).then(a => { console.log('then2'); return a; });
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 3000, 'resolve3');
}).then(a => { console.log('then3'); return a; });
Promise.all([promise1, promise2, promise3])
.then(values => { console.log('then', values); })
.catch(err => { console.log('catch', err); throw err; });
// results:
// > "then1"
// > "catch" "reject2"
// > "then3" <------- WHY?
The script continues to resolve promise3
, even though the final all(...).catch()
throws! Can someone explain why? What can I do to stop the other promises at the point any of them rejects?
setTimeout
somewhere and callclearTimeout
on it if you want that behaviour. – Babismprocess.exit()
? – ThesissetTimeout
inside aPromise
? You may find this presentation useful: youtu.be/cCOL7MC4Pl0 – LyrisPromise
– Lyrisprocess.exit()
. – ThesisclearTimeout
. You need a way to stop a task, first. Promises aren’t really involved at this point. – BabismPromise
s. – Mulligatawny