Promise.myRace = function (iterable) {
return new Promise((resolve, reject) => {
let ret
for (let promise of iterable) {
Promise.resolve(promise).then((resolved) => {
if (ret === undefined) {
ret = resolved
resolve(resolved)
}
}).catch((e) => {
if (ret === undefined) {
ret = e
reject(e)
}
})
}
})
}
const promise1 = new Promise((resolve, reject) => {
setTimeout(reject, 500, 'one');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 1000, 'two');
});
Promise.myRace([promise1, promise2]).then((data) => {
console.log(data)
}).catch(e => console.log(e))
console