MyPromise.promiseAll = function(promises){
return new Promise((resolve, reject)=>{
if(!Array.isArray(promises)) throw new TypeError('promises is not a iterable')
let resolvedCounter = 0
let resolvedResult = []
promises.forEach((p)=>{
p.then(value => {
resolvedCounter++
resolvedResult.push(value)
if(resolvedCounter === promises.length){
return resolve(resolvedResult)
}
},reason => {
return reject(reason)
})
})
})
}
.push会导致返回结果数组的顺序错误
let p1 = Promise.resolve(1)
let p2 = Promise.resolve(2)
let a = Promise.promiseAll([p1,new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(3)
},3000)
}),p2])
// 输出
[1,2,3]