const a = new Promise((resolve, reject) => {
console.log(1)
resolve('结果1')
})
const b = new Promise((resolve, reject) => {
console.log(2)
reject('结果2')
})
.catch((err) => {
console.log('bResult失败', err) //进来了
})
const c = new Promise((resolve, reject) => {
console.log(3)
resolve('结果3')
})
Promise.all([a, b, c])
.then((res) => {
console.log('都结束了',res) // 都结束了 [ '结果1', undefined, '结果3' ]
})
.catch(err => {
console.log('失败', err)
})
打印结果:
1
2
3
bResult失败 结果2
都结束了 [ '结果1', undefined, '结果3' ]
const a = new Promise((resolve, reject) => {
console.log(1)
resolve('结果1')
})
const b = new Promise((resolve, reject) => {
console.log(2)
reject('结果2')
})
const c = new Promise((resolve, reject) => {
console.log(3)
resolve('结果3')
})
Promise.all([a, b, c])
.then((res) => {
console.log('都结束了',res)
})
.catch(err => {
console.log('失败', err) //失败 结果2
})
打印结果:
1
2
3
失败 结果2
如何让promise.all 抛出异常后依然有效
var p1 = new Promise((resolve, reject) => { resolve('p1'); });
var p2 = new Promise((resolve, reject) => { reject('p2'); });
var p3 = new Promise((resolve, reject) => { resolve('p3'); });
Promise.all([p1, p2, p3]
.map(p => p.catch(e => '出错后返回的值')))
.then(values => { console.log('values', values); })
.catch(err => { console.log('err', err); })
打印结果:
values [ 'p1', '出错后返回的值', 'p3' ]
或者使用 Promise.allSettled
(),只要结束了就会执行.then
摘抄: