Zhi-Ling

You can do Everything you want

0%

Written-Promise

Brief IntroEasy way to write promise methods

  • Any
  • All
  • Race
  • Allsettled

Any

只要有一个成功,就返回成功的那个;如果都失败,则返回失败;与 Promise.all () 相反

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function any(promises){
return new Promise((resolve,reject)=>{
let count = 0;
promises.forEach(p=>{
p.then((res)=>{
resolve(res);
},(err)=>{
count++;
if(count === promises.length){
reject(err);
}
}
})
})
})

All

等待所有的元素执行完成后结束,遇到错误后抛出第一个错误并跳出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function all(promises){
return new Promise((resolve,reject)=>{
let count = 0;
let res = [];
const addRes = (index,data)=>{
res[index] = data;
if(++count === promises.length) resolve(res);
}
promises.forEach((p,index)=>{
if(p instanceof Promise){
p.then((res)=>{
addRes(index,res)
},(err)=>{
reject(err);
}
}else{
addRes(index,p)
}
})
})
})

Race

第一个成功或者失败后返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function race(promises){
return new Promise((resolve,reject)=>{
promises.forEach(p=>{
if(p instanceof Promise){
p.then((res)=>{
resolve(res);
},(err)=>{
reject(err);
}
}else{
resolve(p);
}
})
})
})

AllSettled

返回执行的所有元素的执行状态和结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function allSettled(promises){
return new Promise((resolve,reject)=>{
let count = 0;
let res =[];
const addRes = (status,index,data) =>{
res[index] = { status, data };
if(count === promises.length) resolve(res);
}
promises.forEach((p,index)=>{
if(p instanceof Promise){
p.then((res)=>{
addRes("fullfilled",index,res);
},(err)=>{
addRes("rejected",index,err);
}
}else{
addRes(index,p);
}
})
})
})

Welcome to my other publishing channels