Promise.all()
Promise.all(iterable);
iterable
一个可迭代对象,如 Array 或 String。
- 等待所有都完成(或第一个失败)
- 可以传入一个空的可迭代对象
- 执行成功的结果顺序与输入的参数数组实例顺序一致
const p1 = Promise.resolve('success1')
const p2 = '成功2'
const p3 = []
// const p4 = Promise.reject('fail1')
Promise.all([p3, p2, p1]).then(value => {
console.log(value); //[ [], '成功2', 'success1' ]
}).catch(e => {
console.log(e);
})
const p1 = Promise.resolve('success1')
const p2 = Promise.resolve('success2')
const p3 = Promise.resolve('success3')
//执行结果全部成功的情况
Promise.all([p3, p2, p1]).then(value => {
console.log(value); //[ 'success3', 'success2', 'success1' ]
}).catch(e => {
console.log(e);
})
const p1 = Promise.resolve('success1')
const p2 = Promise.resolve('success2')
const p3 = Promise.resolve('success3')
const p4 = Promise.reject('fail1')
const p5 = Promise.reject('fail2')
//第一个失败
Promise.all([p3, p2, p1, p4, p5]).then(value => {
console.log(value);
}).catch(e => {
console.log(e); //fail1 p5的失败被忽略
})
Promise.race()
Promise.race(iterable);
iterable
可迭代对象,类似Array。
返回值
一个待定的 Promise 只要给定的迭代中的一个promise解决或拒绝,就采用第一个promise的值作为它的值,从而异步地解析或拒绝(一旦堆栈为空)
let p1 = new Promise(resolve => {
setTimeout(resolve, 300, 'success1')
})
let p2 = new Promise(resolve => {
setTimeout(resolve, 100, 'success2')
})
Promise.race([p1, p2]).then(value => {
console.log(value); //p2先执行完,打印success2
}).catch (e => {
console.log(e);
})
let p1 = new Promise(resolve => {
setTimeout(resolve, 300, 'success1')
})
let p2 = new Promise(resolve => {
setTimeout(resolve, 100, 'success2')
})
let p3 = new Promise((resolve, reject) => {
setTimeout(reject, 50, 'fail')
})
Promise.race([p1, p2, p3]).then(value => {
console.log(value);
}).catch (e => {
console.log(e); //fail 有失败的情况先执行完毕,打印失败的原因
})