Promise.all、Promise.allSettled及Promise.race实现
1、Promise.all的实现
原理
:Promise.all的参数为promise列表,若所有promise任务都成功则返回resolve值的列表,如果有一个promise任务失败则返回失败,且Promise.all返回一个Promise对象,实现代码如下:
//实现promise.all
Promise._all = (promises) =>{
return new Promise((resolve,reject) => {
let count = promises&&promises.length || 0;
let resolves = [];
for(let promise of promises){
promise.then(res => {
resolves.push(res)
count--
if(count === 0){
resolve(resolves)
}
}).catch(err => {
reject(err)
})
}
})
}
2、Promise.allSettled实现
原理
:Promise.allSettled的参数为promise列表,不管任务失败还是成功,都将返回一个数组,该数组记录任务状态及对应的value或reason,且Promise.allSettled返回一个Promise对象,实现如下:
//实现Promise.allSettled
Promise._allSettled = (promises) => {
const resolveFn = value => ({status:'fulfilled',value});
const rejectFn = reason => ({status:'rejected',reason});
return Promise._all(
promises instanceof Array
?promises.map( promise =>
Promise.resolve(promise).then(resolveFn,rejectFn)
)
:[]
)
}
3、Promise.race实现
原理
:Promise.race的参数为promise数组,返回一个 promise 实例,且返回的 promise 实例的 resolve 或 reject 的回调结果要求都是最先得到的,实现如下:
//实现Promise.race
Promise._race = function(promises){
if(!promises instanceof Array) return;
return new Promise((resolve,reject) => {
for( let promise of promises){
promise.then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
}
})
}