I was writing polyfill for Promise.race() method using the below code snippet.
const promise = new Promise((resolve, reject) => {
resolve('promise resolved');
});
const promise2 = Promise.resolve('promise2 resolved');
function raceCopy(promises) {
return new Promise(function (resolve, reject) {
for (var index = 0; index < promises.length; index++) {
Promise.resolve(promises[index])
.then(resolve)
.catch(reject);
}
});
}
raceCopy([Promise.reject('copy rejected'), promise, promise2])
.then((response) => console.log(response))
.catch((error) => console.error(error));
But instead of giving the error "copy rejected" in the console, it is showing "promise resolved". I do not understand How and Why it is working like this?
What I tried?
- I used the existing Promise.race() API, and it is giving me the correct result "copy rejected".
Promise.race([Promise.reject('copy rejected'), promise, promise2])
.then((response) => console.log(response))
.catch((error) => console.error(error));
- Second, I changed the implementation of the
raceCopy()
. Something like this,
function raceCopy(promises) {
return new Promise(function (resolve, reject) {
for (var index = 0; index < promises.length; index++) {
Promise.resolve(promises[index]).then(resolve, reject);
}
});
}
And It is also giving the correct result.
What I'm not understanding? If all the implementations are the same then Why are the results not the same for all? What am I missing here?