I'm using async
await
in my NodeJs code and the code structure is something as follows.
async function main(){
try {
await someFunctionThatReturnsRejectedPromise()
} catch(e) {
console.log(e)
}
}
async function someFunctionThatReturnsRejectedPromise() {
try {
await new Promise((resolve,reject) => {
setTimeout(() => {
reject('something went wrong')
}, 1000);
})
} catch(e) {
return Promise.reject(e)
} finally {
await cleanup() // remove await here and everything is fine
}
}
function cleanup() {
return new Promise(resolve => {
setTimeout(() => {
resolve('cleaup successful')
}, 1000);
})
}
main();
In the finally block, I'm doing some async
cleanup that will surely resolve.
But this code is throwing PromiseRejectionHandledWarning
(node:5710) UnhandledPromiseRejectionWarning: something went wrong
(node:5710) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 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(). (rejection id: 1)
(node:5710) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
something went wrong
(node:5710) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
As far as I understand, I'm not leaving any promise unhandled here.
What am I doing wrong? Should finally
block by synchronous by design? If yes, why so?
Update 1:
If I convert someFunctionThatReturnsRejectedPromise
to good ol' then
and catch
, it works with no problems:
function someFunctionThatReturnsRejectedPromise() {
return (new Promise((resolve,reject) => {
setTimeout(() => {
reject('something went wrong')
}, 1000);
})).catch(e => {
return Promise.reject(e)
}).finally(() => {
return cleanup()
})
}
Update 2: (Understood the problem)
If I await
the returning Promise, problem is solved.
return await Promise.reject(e)
And this makes me understand what I was doing wrong.
I was breaking the await
chain (partially synonymous to not returning a Promise
in then
/catch
syntax).
Thanks everyone :)