Promise.all 接受由多个 promise 组成的数组作为参数
当数组中所有的 promise 都 resolve 时,返回这些 promise 结果组成的数组
当任意一个 promise reject 时,则终止执行,抛出错误
Promise.all2 = (promiseList) => {
return new Promise((resolve, reject) => {
let result = []
let length = promiseList.length
let count = 0
promiseList.forEach((promise, index) => {
promise.then(data => {
result[index] = data
count += 1
if(count === length -1) {
resolve(result)
}
}, (reason) => reject(reason))
})
})
}
Promise.all2([Promise.resolve(1), Promise.resolve('foo'), Promise.resolve(3)])
.then(data => console.log(data), reason => console.error(reason))
// [1, 'foo', 3]
Promise.all2([Promise.resolve(1), Promise.reject('foo'), Promise.resolve(3)])
.then(data => console.log(data), reason => console.error(reason))
// error foo