I have a small custom polyfill for Promise.all and while trying to execute it I see that update of array(errorList) in catch block is not working. Can someone please help me understand what am I missing.
Promise.customAll = function (promisesList) {
let errorList = [];
let resultList = [];
return new Promise((resolve, reject) => {
promisesList.forEach(async (promise, index) => {
try {
let result = await promise;
resultList[index] = (result);
} catch (err) {
errorList.push(err);
}
});
if (errorList.length) {
reject(errorList);
} else {
resolve(resultList);
}
});
};
Here is how I am using it. For above code I am expecting my promise tp go to catch block but its going to then block and printing [ 'FirstPromise', <1 empty item>, '3rd Promise' ]
Promise.customAll([Promise.resolve("FirstPromise"), Promise.reject("Error in 2nd Promise"), Promise.resolve("3rd Promise")])
.then((val) => {
console.log(val);
})
.catch((err) => {
console.log(err);
});
Promise.customAll = function (promisesList) {
let errorList = [];
let resultList = [];
return new Promise((resolve, reject) => {
promisesList.forEach(async (promise, index) => {
try {
let result = await promise;
resultList[index] = result;
if (index === promisesList.length - 1) {
if (errorList.length) {
reject(errorList);
} else {
resolve(resultList);
}
}
} catch (err) {
errorList.push(err);
}
});
});
};
As suggested by @youdateme, moved my logic in forEach callback as its async that solved the issue.