我还以为是先手写promise,再实现all方法呢,没想到这么简单。。。
/**
* 手写 promise.all
*/
function promiseAll(args) {
return new Promise((resolve, reject) => {
const promiseResult = []
let iteratorIndex = 0
let fullCount = 0
for(const item of args) {
let resultIndex = iteratorIndex;
iteratorIndex += 1
Promise.resolve(item).then(res => {
promiseResult[resultIndex] = res
fullCount += 1
if(fullCount === args.length) {
resolve(promiseResult)
}
}).catch(err => {
reject(err)
})
}
if(iteratorIndex === 0) {
resolve(promiseResult)
}
})
}
if(!Promise.all) {
Promise.all = promiseAll
}
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2)
}, 2000)
})
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve(3)
reject(3)
}, 3000)
})
promiseAll([p1, p2, p3]).then(res => {
console.log(res)
}).catch(err => {
console.error('err: ', err)
}).finally(() => {
console.log('finally')
})
标签:resolve,const,promiseResult,err,JS,Promise,reject,手写 From: https://www.cnblogs.com/zjy4fun/p/17523939.html