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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…