Last active
February 22, 2021 07:33
-
-
Save mucaho/74cfd78fa5b515eae910eeff42dfe819 to your computer and use it in GitHub Desktop.
Example code demonstrating the not immediately apparent issue of a promise rejecting while another one is being awaited.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function main() { | |
const rej = Promise.reject('err') | |
// the following line is needed, | |
// otherwise UnhandledPromiseRejectionWarning is thrown | |
// which can't be caught anywhere else (not even by async caller)! | |
// can be NOOP though, if error handling may be delayed to below catch block | |
rej.catch(e => console.log(e)) // logs 'err' | |
const del = new Promise((resolve) => { | |
setTimeout(() => resolve('del'), 100) | |
}) | |
try { | |
await del | |
} catch (e) { | |
console.log(e) | |
} | |
try { | |
await rej | |
} catch (e) { | |
console.log(e) // logs 'err' | |
} | |
console.log('fin') // logs 'fin' | |
} | |
/** | |
* OUTPUT: | |
* err | |
* err | |
* fin | |
*/ | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment