How to handle javascript promise in various scenario

Yash Govindani
Geek Culture
Published in
2 min readMay 30, 2021

--

While working on a project at Virtual Cybertrons Pvt. Ltd., I faced difficulty in handling scenarios in javascript which requires code to be executed in synchronous fashion and using promises for the purpose.

Since there were no proper solution for the purpose so I decided to do it by myself. I will discuss these scenarios one by one.

Let’s start with scenario 1, in which we have to call a function (not returning anything) more than once, one after the other in synchronous fashion.

Code snippet with problem for scenario 1

Expected Output :
Sum of 102 and 308 :
410
Sum of -1 and 38 :
37

Actual Output :
Sum of 102 and 308 :
Sum of -1 and 38 :
410
37

Actual output differs from expected because code executes in asynchronous fashion. The above code can be resolved using Promise. Below is the proper code to handle it.

Code Snippet with solution for scenario 1

Let’s move to second scenario, in which we have to call a function (returning something) more than once, one after the other in synchronous fashion.

Code Snippet with problem to be resolved

Expected Output :
Sum of 102 and 308 : 410
Sum of -1 and 38 : 37

Actual Output :
Sum of 102 and 308 : undefined
Sum of -1 and 38 : undefined

Again, actual output differs from expected because code executes in asynchronous fashion. The above code can be resolved using Promise. Below is the proper code to handle it.

Code Snippet with solution for scenario 2

Though in both the scenarios discussed above we have achieved the working we want, but as the complexity of the code increases the readability of the code decreases and the code may get difficult to understand. So to make code easy to understand we can use async-await.

Before getting to solution for above scenarios using async-await, it is important to understand how async-await works actually.

Below is the example to understand working of async-await.

Code snippet with misconception

Expected Output :
calling someFunction
someFunction got called with argument : 10
after someFunction got completely executed

Actual Output :
calling someFunction
after someFunction got completely executed
someFunction got called with argument : 10

Correct way to do is below :

Code Snippet with correct way to use async-await

Solution code for scenario 1 using async-await :

Solution code for scenario 2 using async-await :

Note : In last snippet whatever is passed as an argument while call to resolve is assigned to sum1 (or sum2 in next call).

There are more scenarios and solution for handling rejections in async-await to be discussed later in article ‘How to handle javascript promise rejection in case of async-await’.
Thank You.

--

--