- 入参必须实现iterator接口,一般为数组
- 全部成功才算成功,有一个失败就失败, 如果成功,结果顺序和入参顺序保持一致
- 返回一个新的promise,
Promise._all = function (promises) {
if (!promises instanceof Array) throw 'promises must be an array'
const length = promises.length
let count = 0
const ret = []
if (!length) return []
return new Promise((resolve,reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(v => {
count++
ret[i] = v
count === length && resolve(ret)
}, r => {
reject(r)
})
}
})
}
const doAsyncTask = (fn, timeout) => setTimeout(() => fn(), timeout)
const p1 = new Promise((resolve, reject) => doAsyncTask(()=>{reject(1)},2000))
const p2 = new Promise((resolve, reject) => doAsyncTask(()=>{resolve(2)},1000))
const p3 = new Promise((resolve, reject) => doAsyncTask(()=>{resolve(3)},3000))
const res = Promise._all([p1,p2,p3])
res.then(v=>console.log(v),r=>console.log(r))
console.log(res);