// 有一个失败则返回失败的结果,全部成功返回全成功的数组
Promise.all = function (promiseList = []) {
return new Promise((resolve, reject) => {
const result = []
let count = 0
if (promiseList.length === 0) {
resolve(result)
return
}
for (let i = 0; i < promiseList.length; i++) {
Promise.resolve(promiseList[i]).then(res => {
result[i] = res
count++
if (count === promiseList.length) {
resolve(result)
}
}).catch(e => {
reject(e)
})
}
})
}
// 返回第一个成功或失败的结果
Promise.race = function (promiseList = []) {
return new Promise((resolve, reject) => {
if (promiseList.length === 0) {
return resolve([])
}
for (let i = 0; i < promiseList.length; i++) {
Promise.resolve(promiseList[i]).then(res => {
resolve(res)
}).catch(e => {
reject(e)
})
}
})
}
// 无论成功约否都返回,但是会添加一个 status 字段用于标记成功/失败
Promise.allSettled = function (promiseList = []) {
return new Promise((resolve, reject) => {
const result = []
let count = 0
const addRes = (i, data) => {
result[i] = data
count++
if (count === promiseList.length) {
resolve(result)
}
}
if (promiseList.length === 0) return resolve(result)
for (let i = 0; i < promiseList.length; i++) {
Promise.resolve(promiseList[i]).then(res => {
addRes(i, { status: 'fulfilled', data: res })
}).catch(e => {
addRes(i, { status: 'rejected', data: e })
})
}
})
}
// 和 Promise.all 相反,全部失败返回失败的结果数组,有一个成功则返回成功结果
Promise.any = function (promiseList = []) {
return new Promise((resolve, reject) => {
if (promiseList.length === 0) return resolve([])
let count = 0
const result = []
for (let i = 0; i < promiseList.length; i++) {
Promise.resolve(promiseList[i]).then(res => {
resolve(res)
}).catch(e => {
count++
result[i] = e
if (count === promiseList.length) {
reject(new AggregateError(result))
}
})
}
})
}
标签:count,resolve,promiseList,length,race,Promise,result,allSettled
From: https://www.cnblogs.com/samsara-yx/p/17000405.html