2795. 并行执行 Promise 以获取独有的结果
2025年6月25日小于 1 分钟
2795. 并行执行 Promise 以获取独有的结果
type FulfilledObj = {
status: 'fulfilled'
value: string
}
type RejectedObj = {
status: 'rejected'
reason: string
}
type Obj = FulfilledObj | RejectedObj
function promiseAllSettled(functions: Function[]): Promise<Obj[]> {
return new Promise((reslove) => {
const result = Array.from({ length: functions.length })
let endCount = 0
for (let i = 0; i < functions.length; i++) {
functions[i]()
.then((value: string) => (result[i] = { status: 'fulfilled', value }))
.catch((reason: string) => (result[i] = { status: 'rejected', reason }))
.finally(() => {
endCount += 1
if (endCount === functions.length) {
reslove(result as Obj[])
}
})
}
})
}
/**
* const functions = [
* () => new Promise(resolve => setTimeout(() => resolve(15), 100))
* ]
* const time = performance.now()
*
* const promise = promiseAllSettled(functions);
*
* promise.then(res => {
* const out = {t: Math.floor(performance.now() - time), values: res}
* console.log(out) // {"t":100,"values":[{"status":"fulfilled","value":15}]}
* })
*/