fe-interview
fe-interview copied to clipboard
手动实现一个promise.all
https://juejin.im/post/6844904067798401038#comment
function PromiseAll(promises) {
return new Promise((resolve,reject) => {
if(!Array.isArray(promises)){
return reject(new TypeError('arguments muse be an array'))
}
const LEN = promises.length
let counter = 0
let result = new Array(LEN)
for(let i = 0; i < LEN; i++){
Promise.resolve(promises[i]).then((value) => {
counter++;
result[i] = value;
if(counter === LEN){
return resolve(result)
}
}, (reason) => {
return reject(reason)
})
}
})
}
// 测试
const pro1 = new Promise((res,rej) => {
setTimeout(() => {
res('1')
},1000)
})
const pro2 = new Promise((res,rej) => {
setTimeout(() => {
res('2')
},2000)
})
const pro3 = new Promise((res,rej) => {
setTimeout(() => {
res('3')
},3000)
})
const proAll = PromiseAll([pro2, pro3, pro1])
.then(res =>
console.log(res) // 3秒之后打印 [ "2", "3", "1"]
)
.catch((e) => {
console.log(e)
})