概念
The Promise.race(iterable) method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
意思是Promise.race会返回参数中第一个执行完毕的promise的结果(无论是已完成还是已拒绝)
《深入理解ES6》中的错误
源代码
let p1 = new Promise(function(resolve, reject) {
resolve(42);
});
let p2 = Promise.reject(43);
let p3 = new Promise(function(resolve, reject){
resolve(44);
});
let p4 = Promise.race([p1, p2, p3]);
p4.catch(function(value) {
console.log(value); // 43
});
书中概念讲的是对的。
但是关于这段代码的描述有问题,作者认为执行结果应该是p2的已拒绝, 打印43。
但是其实执行的是p1的已解决,所以不会打印任何值,如果改成p4.then,则会打印42。
p4.then(function(value) {
console.log(value); // 42
});
所以一般写法是then和catch都要处理
p4.then(function(value) {
console.log(value); // 42
}).catch(function(value) {
console.log(value);
});