I am working on custom implementation of Promise.allSettled in NodeJs. When I implement using Promise.then it works perfectly. But when I implement using Async/Await it throw the error.
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason “Failed”.] {
code: ‘ERR_UNHANDLED_REJECTION’
}.
function myCustomAllSettled2(promises){
return new Promise(async (resolve, reject) => {
try{
let completedCount = 0
let results = []
for(let i=0; i<promises.length; i++){
try{
let result = await promises[i]
results[i] = {"status": "fulfilled", "value": result}
}
catch(ex){
results[i] = {"status": "rejected", "reason": ex.message || ex}
}
finally{
completedCount += 1
if(completedCount === promises.length){
resolve(results)
}
}
}
}
catch(ex){
reject(ex)
}
})
};
function myCustomAllSettled(promises){
return new Promise((resolve, reject) => {
let completedCount = 0
let results = []
for(let i=0; i<promises.length; i++){
promises[i].then(result => {
results[i] = {"status": "fulfilled", "value": result}
}).catch(ex => {
results[i] = {"status": "rejected", "reason": ex.message || ex}
}).finally(() => {
completedCount += 1
if(completedCount === promises.length){
resolve(results)
}
})
}
})
};
(async()=>{
try{
let s = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Success')
}, 400)
})
let f = new Promise((resolve, reject) => {
setTimeout(() => {
reject('Failed')
}, 300)
})
let promises = [s,f]
//This works well
myCustomAllSettled(promises).then(results => {
results.forEach(result => {
if(result.status === 'fulfilled'){
console.log('Success : ' , result.value)
}
else{
console.log('Failed : ' , result.reason)
}
});
})
let s2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Success')
}, 400)
})
let f2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject('Failed')
}, 300)
})
let promises2 = [s2,f2]
//This throws error
let results = await myCustomAllSettled2(promises2)
results.forEach(result => {
if(result.status === 'fulfilled'){
console.log('Success : ' , result.value)
}
else{
console.log('Failed : ' , result.reason)
}
});
}
catch(ex){
console.log(ex)
}
})();
I tried implementing using Promise.then and it worked. But When I try to implement using async/await it throws error.
Raj Kumar Rurhi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.