How to handle javascript promise rejection in case of async-await

Yash Govindani
2 min readJun 19, 2021

This article is in continuation to article ‘How to handle promise in various scenarios in javascript’.

Before moving to next scenario, let’s create a synchronous function to take user input, which we will use in further scenarios.

Code snippet with input function is loading… .. .
Code snippet with input function

Let’s start with scenario 3, in which we have used async-await to write program in synchronous fashion and required to handle promise rejections.

Code with problem :

Code snippet with rejection problem

When divisor is non-zero :
Input :
Enter dividend : 10
Enter divisor : 5
Output : 2

When divisor is zero :
Input :
Enter dividend : 10
Enter divisor : 0
Output :
(node:928) UnhandledPromiseRejectionWarning: Divisor can not be zero
(Use `node — trace-warnings …` to show where the warning was created)
(node:928) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag ` — unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:928) [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.

Solution : The best way to handle promise rejection in case of async-await is to put the part of code that may cause rejection in try catch.

Code snippet with rejection solution

Thanks Virtual Cybertrons Pvt. Ltd. for encouraging me to write article.

--

--