How to handle promise rejections in Async Await

A promise in JavaScript can be resolved if the code execution completed as expected, or it can be rejected if there are any errors. When using async await, you may be awaiting a promise, but if something goes wrong, then you may get an ‘Unhandled Promise Rejection’ error. This happens because each promise rejection needs to be handled within a try-catch block.

Suppose you are fetching user details from Amazon Cognito. Instead of writing:

cognitoUser = await cognito.adminGetUser(Cognitoparams).promise()

The correct method would be:

try {
    cognitoUser = await cognito.adminGetUser(Cognitoparams).promise()
  } catch (error) {
    cognitoUser = null;   

The first method (without try-catch) would work as long as the promise gets resolved. However, if there is a promise rejection, the code would break at that point and throw an error like the one below:

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 “…”

If you are interested in a more detailed explanation with various scenarios covered, you can refer to this excellent blog post on Medium.

I hope you liked this article. For more articles on IoT in general, check out

Leave a comment

Your email address will not be published.