// 判断是否是promise
const isPromise = value =>{
if((typeof value === 'object' && value !== null) ||typeof value === 'function'){
return typeof value.then === 'function'
}
return false;
}
Promise.all = function (promises) {
return new Promise((resolve,reject)=>{
let arr = [];
let i = 0;
let processData = (index,data)=>{
arr[index] = data; // 保证返回结果顺序
if(++i === promises.length){
resolve(arr);
}
}
for(let i = 0; i< promises.length;i++){
let current = promises[i];
if(isPromise(current)){
current.then(data=>{
processData(i,data)
},reject)
}else{
processData(i,current);
}
}
})
}
//Promise.all可以解决异步并发问题,并且返回的结果按照调用的顺序进行存储。全部成功后才成功否则执行失败逻辑
//race只采用第一个成功或者失败的结果
Promise.race = function (promises) {
return new Promise((resolve, reject) => {
// 谁返回的结果最快 就用谁的
for (let i = 0; i < promises.length; i++) {
let current = promises[i];
if (isPromise(current)) {
current.then(resolve, reject)
} else {
resolve(current);
}
}
})
}
应用场景
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('成功');
}, 3000);
})
function wrap(p){
let abort;
let p1 = new Promise((resolve,reject)=>{
abort = reject;
});
let newPromise = Promise.race([p1,p])
newPromise.abort = abort
return newPromise
}
let p1 = wrap(p);
p1.then(data => {
console.log('success', data)
}, err => {
console.log('error', err)
})
setTimeout(() => {
p1.abort('超过2s了');
}, 2000);
//借助race的特点,可以实现立即中断promise变为失败态。常用作超时操作