Promise.all 如何防止某一个promise失败而使整个promise失败
原理:
由于Promise内部实现中,是否resolve由内部成功数组的长度和传入数组的长度进行比较的,那么在给失败的Promise在catch的时候返回一个reolve状态就可以啦。
上代码:
正常失败情况:
let p1 = new Promise((resolve, reject) => { setTimeout(resolve, 1000, 'one'); }); let p2 = new Promise((resolve, reject) => { setTimeout(resolve, 2000, 'two'); }); let p3 = new Promise((resolve, reject) => { setTimeout(resolve, 3000, 'three'); }); let p4 = new Promise((resolve, reject) => { setTimeout(resolve, 4000, 'four'); }); let p5 = new Promise((resolve, reject) => { reject('错误'); }) Promise.all([p1, p2, p3, p4, p5]).then(values => { console.log({values}); }, reason => { console.log({reason});// reject });
处理后:
let p1 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'one');
});
let p2 = new Promise((resolve, reject) => {
setTimeout(resolve, 2000, 'two');
});
let p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 3000, 'three');
});
let p4 = new Promise((resolve, reject) => {
setTimeout(resolve, 4000, 'four');
});
let p5 = new Promise((resolve, reject) => {
reject('错误');
})
function catchFun(items) {
return items.map(item => item.catch((err) => Promise.resolve(err)))
}
Promise.all(catchFun([p1, p2, p3, p4, p5])).then(values => {
console.log({values});
}, reason => {
console.log({reason}); // reject
});