Hello friends, this is the last article in the "Principles of Handwritten Promise Series". Although we have learned a lot about promises, we are still on the road to 异步编程
There is still a long way to go, and I will write a separate article later to discuss the use of async/await, a better asynchronous practice.
The current chapter discusses the usage and encapsulation of the Promise.race method.
From the definition of race
we can know that it means 比赛、赛跑
. In fact, it depends on which promise object is executed first and returns the promise object which is executed first. Results, whether the outcome is success or failure. The slogan is:不求最好,只求最快
.
Let’s look at how Promise.race is used:
let p1 = new Promise((resolve, reject) => {
resolve("111");
});
let p2 = Promise.resolve("222");
let p3 = Promise.resolve("333");
let result = Promise.race([p1, p2, p3]); // 参数为 promise 对象组成的数组
console.log(result);
Above resolve("111")
is executed first, so the returned result is "111"
.
Let’s look at the following asynchronous execution method:
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("111");
})
});
let p2 = Promise.resolve("222"); // 改变状态为失败 reject
let p3 = Promise.resolve("333");
let result = Promise.race([p1, p2, p3]); // 参数为 promise 对象组成的数组
console.log(result);
In the above code, resolve("111")
becomes asynchronous execution, so the first execution at this time is resolve("222")
; so the result returns "222"
.
Let’s look at an example of failure:
let p1 = new Promise((resolve, reject) => {
reject("111");
});
let p2 = Promise.resolve("222"); // 改变状态为失败 reject
let p3 = Promise.resolve("333");
let result = Promise.race([p1, p2, p3]); // 参数为 promise 对象组成的数组
console.log(result);
When reject("111")
is executed, the status of the current promise object becomes failed, so it is returned directly.
Promise.race feature point:
- Returns a promise object;
- The status result of the returned promise object is the status result of the promise object executed first in the array.
Wrapping code of Promise.race method:
Promise.race = function (promiseArray) {
// 返回一个 promise 对象
return new Promise((resolve, reject) => {
// 按优先级顺序执行 promise 对象,直接返回最先执行完成的 promise 对象的结果
for (let i = 0; i < promiseArray.length; i++) {
let p = promiseArray[i];
p.then(value => {
resolve(value);
}, reason => {
reject(reason)
})
}
})
}