Promise, Async, Await— Understanding and Implementation

Souvik Brahma
Fasal Engineering
Published in
3 min readJun 2, 2021

Overview

Here in this article, we are going to discuss two of the most fundamental topics in Js which are Promise and Async/Await using real-life examples.

Why do we need to wait?

We wait for a function or a method to return a result because our next operation would depend on the result of this function or method. Let's consider a network call. You want some data from a remote server, so-called an API. The response time of an API depends on multiple factors, so the execution pointer has to wait for the API response to arrive first.

Callback

In Javascript, we use a callback. You call a function and then wait for it to return a value. Once it returns a value, you write another function and pass that function as a param, which handles the response.

Here ‘addNumbers’ is a function that has got three parameters in it i.e first number ‘a’, the second number ‘b’, and an anonymous function that gets called from the declaration block of ‘addNumbers’ after processing the sum of the numbers. So here you can see, after processing of data, ‘addNumbers’ is providing the ‘processedData’ to callback to take it further.

Now, what if you are writing a function with a chain of callback function? You surely don’t want to write all of them in a nested format. Refer to the below image.

Callback Hell

Code with callback hell is not scalable. It is hard to read, hard to debug, and easy to break while executing. So to avoid callbacks we use Promises or Async/Await.

Promise and Async/Await

Let take this discussion forward with a code snippet.

In the code snippet, we came across three important keywords.

A promise is a type of Function that gets processed and returns a resolve or reject obj.

async: an async function will always return a Promise

await: using await before calling an async function is to wait for the Promise to return the resolved or rejected value.

So using Promise async and await we can write better code by removing the callbacks. Let’s rewrite the first example of ‘addNumbers’ using promise.

Here addNumber is an asynchronous function that returns a Promise, then await waits for the Promise to get resolved.

Error Handling in Promise

Usage of reject in Promise makes error handling easy. Whenever a Promise function returns a reject obj its comes to the catch block directly as a param. Thus error gets handled easily inside a catch block.

In the above snippet, as the Promise function is returning reject, it will go inside the catch block. Thus even after writing 100 lines of code inside the try block using await, all the errors will get reported at the very small catch block.

Conclusion

A Promise can be written in many ways. The promise gives us an extensive set of ways to write our codes n an optimized way. For more understanding of Promise, try Promise.all() Promise chaining.

--

--