带你读《现代Javascript高级教程》二十七、实现符合Promise/A+规范的Promise(5)https://developer.aliyun.com/article/1349503?groupCode=tech_library
2)实现Promise.race: Promise.race方法接收一个可迭代对象(如数组或类数组对象),并返回一个新的Promise,该Promise将与最先解决或拒绝的输入Promise具有相同的状态。
Promise.race = function (promises) { return new Promise((resolve, reject) => { for (let i = 0; i < promises.length; i++) { promises[i] .then((value) => { resolve(value); }) .catch((reason) => { reject(reason); }); } });};
使用示例:
const promise1 = new Promise((resolve) => setTimeout(() => resolve(1), 1000));const promise2 = new Promise((resolve) => setTimeout(() => resolve(2), 2000));const promise3 = new Promise((resolve) => setTimeout(() => resolve(3), 1500)); Promise.race([promise1, promise2, promise3]) .then((value) => { console.log(value); // 输出: 1 }) .catch((reason) => { console.error(reason); });
- 参考资料
Promise/A+ 规范官方文档:https://promisesaplus.com/