手写Promise.all
Promise.myAll = (promises) => {
return new Promise((rs, rj) => {
let count = 0
let result = []
const len = promises.length
if (len === 0) {
return rs([])
}
promises.forEach((p, i) => {
Promise.resolve(p).then((res) => {
count += 1
result[i] = res
if (count === len) {
rs(result)
}
}).catch(rj)
})
})
}
const p1 = Promise.resolve(1)
const p2 = new Promise((resolve) => {
setTimeout(() => resolve(2), 1000)
})
const p3 = new Promise((resolve) => {
setTimeout(() => resolve(3), 3000)
})
const p4 = Promise.reject('err4')
const p5 = Promise.reject('err5')
const p11 = Promise.myAll([p1, p2, p3])
.then(console.log)
.catch(console.log)
const p12 = Promise.myAll([p1, p2, p4])
.then(console.log)
.catch(console.log)
const p13 = Promise.myAll([p1, p4, p5])
.then(console.log)
.catch(console.log)