Promise.All接收一个可迭代对象,当里面所有promise成功,则返回一个带有所有promise结果的数组;只要有一个失败,则整个Promise.All失败
Promise.resolve能将一个值转换为一个Promise,而如果接受的值本身就是promise,则原样返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
Promise.myAll = (promiseArr) => { let resolve, reject const promiseResult = new Promise((res, rej) => { resolve = res reject = rej }) const result = []
let count = 0 let fulfilledCount = 0
for (const p of promiseArr) { const i = count count++ Promise.resolve(p).then((res) => { result[i] = res fulfilledCount++ if (fulfilledCount === count) { resolve(result) } }, (err) => { reject(err) }) }
if (count === 0) { resolve(result) }
return promiseResult }
const test = async () => { const promise1 = new Promise((res, rej) => { setTimeout(() => { res('114') }, 2000) }) const promise2 = new Promise((res, rej) => { setTimeout(() => { res("omg") }, 5000) }) const promise3 = new Promise((res, rej) => { res("yajue") })
const res = await Promise.myAll([promise1, promise2, promise3, 514, '只因你太美']) console.log(res) }
test()
|