Promise学习(2)

Promise.all()

1
2
3
4
5
6
7
8
9
10
11
12
13
function setTime(time = 0, isSuccess = true) {
return new Promise((res, rej) => {
setTimeout(() => {
console.log(666);
isSuccess && res(`成功:${time}`);
!isSuccess && rej(`失败:${time}`);
}, time);
});
}

Promise.all([setTime(100), setTime(200), setTime(300)])
.then(res => console.log(res)) // (3) ["成功:100", "成功:200", "成功:300"]
.catch(err => console.log(err));

它会等数组中的所有Promise实例都执行成功,才会执行.then()中的响应函数,并且返回每个实例的参数,组合成数组。

1
2
3
Promise.all([setTime(400, false), setTime(200, false), setTime(300)])
.then(res => console.log(res))
.catch(err => console.log(err));

当有一个或以上Promise实例执行失败时,就会直接执行.catch()中的响应函数,并且返回首个失败Promise实例的错误信息。


Promise.race()

1
2
3
4
5
6
7
8
9
10
11
Promise.race([setTime(300), setTime(200), setTime(400)])
.then(res => console.log(res)) // 成功:200
.catch(err => console.log(err));

Promise.race([setTime(300, false), setTime(200, false), setTime(400)])
.then(res => console.log(res))
.catch(err => console.log(err)); // 失败:200

Promise.race([setTime(300, false), setTime(200), setTime(400)])
.then(res => console.log(res)) // 成功:200
.catch(err => console.log(err));

Promise.all()不一样,Promise.race()当其中一个实例执行完成时,就算完成。由该完成的实例,决定走.then()还是.catch()的响应函数。


参考链接:https://www.jianshu.com/p/1b63a13c2701



Promise学习(2)
作者
墨陌默
发布于
2020年9月7日
许可协议