//实现Promise.race()
/**
* @param {Promise[]} arr
* @return {Promise}
*/
const p1 = new Promise((r, j) => setTimeout(r, 1000, "oneSuccess"))
const p2 = new Promise((r, j) => setTimeout(r, 2000, "twoSuccess"))
const p3 = new Promise((r, j) => setTimeout(j, 500, "threeError"))
Promise.prototype.myRace = function (arrP) {
let hasValue = false
let hasError = false
return new Promise((resolve, reject) => {
for (let i = 0; i < arrP.length; i++) {
arrP[i].then(data => {
!hasValue && !hasError && resolve(data)
hasValue = true
}, error => {
!hasValue && !hasError && reject(error)
hasError = true
})
}
})
}
Promise.prototype.myRace([p1, p2, p3]).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
})