Reject a JavaScript Promise in a try-catch block [Tech Interview Quiz]
Promises are a useful tool in JavaScript for managing asynchronous tasks and handling errors.
When a promise is rejected, it enters a “rejected” state and triggers a rejection handler, which allows you to handle the error.
In tech interviews, you’ll be frequently asked to explore the different ways to handle promise rejection in JavaScript as incorrect handling of rejected promises leads to bugs and crashes.
Consider the code snippet and detemine how the program would behave.
Code snippet as a picture
|
|
What happens if you try to reject the promise inside of the JavaScript try/catch
block. Will the error be caught in the catch
block?
Explanation
Regular
try/catch
blocks only catch errors that appear in the synchronous code.As the
Promise
in the second line doesn’t have its own asynchronous.catch
block, the rejection will be left unhandled.An
UnhandledPromiseRejectionWarning
will be raised and the code inside of the regularcatch
block will not be executed.
Answer
The error will not be caught and the message
the error was caught!
will NOT be logged to the console.