解决方法 => Promise.allSettled()
我们都知道Promise.all()具有并发执行异步的能力 但是如果其中某个任务但凡有一个出现reject异常错误 所有任务都会挂掉 所以Promise.allSettled()将是最棒的处理并发执行异步的方法
看段代码 => Promise.all走向catch
const promise1 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('promise1')
}, 3000)
})
}
const promise2 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('promise2')
}, 1000)
})
}
const promise3 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('error promise3')
}, 2000)
})
}
// Promise.all 会走到catch里面
Promise.all([promise1(), promise2(), promise3()]).then(res => {
console.log('成功', res);
}).catch(err => {
console.log('失败', err); // 报错 失败 error promise3 错误信息提示promise3导致的
})
再看Promise.allSettled()的处理
const promise1 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('promise1')
}, 3000)
})
}
const promise2 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('promise2')
}, 1000)
})
}
const promise3 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('error promise3')
}, 2000)
})
}
Promise.allSettled([promise1(), promise2(), promise3()]).then(res => {
console.log('成功1', res);
}).catch(err => {
console.log('失败1', err);
})
// Promise.allSettled 不管有没有错误,三个的状态都会返回
// 上面的方法返回
成功1 [
{ status: 'fulfilled', value: 'promise1' },
{ status: 'fulfilled', value: 'promise2' },
{ status: 'rejected', reason: 'error promise3' }
]