# 实现 Promise.race
# Promise.race() 方法返回一个 promise,一旦迭代器中的某个 promise 解决或拒绝,返回的 promise 就会解决或拒绝。
const t = new Promise((resolve, reject) => {
setTimeout(() => {
// resolve("success");
reject("t");
}, 1000);
});
const h = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
// reject("h");
}, 2000);
});
Promise.myRace = function (promises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) return;
const len = promises.length;
for (let i = 0; i < len; i++) {
Promise.resolve(promises[i])
.then((r) => {
resolve(r);
})
.catch((e) => {
reject(e);
});
}
});
};
Promise.myRace([t, h])
.then((r) => {
console.log(r, "r");
})
.catch((e) => {
console.log(e, "e");
});
//t e