JS Promises: An Overview

Chetan Chauhan
3 min readFeb 23, 2021

In this article we are going to talk about one of the most discussed concept in JavaScript i.e. Promises and how it contributes to the asynchronous nature of JavaScript.

Introduction

A promise is an object which guarantees that there will be some value available in the future. This “some value” could be the expected return value or an error.

This allows the JavaScript to process asynchronously as it can wait for some value to be returned and execute defined logic afterwards. By asynchronous here we mean that it can move forward on further code and execute the part where response is awaited later, by handling the promise when it returns the value.

.then()

Promise object takes a callback function which accepts two arguments resolve and reject. This callback function is called executor function. It uses resolve function if the promise is successful and reject if it is not.

We can use then() to handle the promise in case of success . The then() block will be called when promise is successful.

Edit Code:- Online code

· You can see in above example during execution firstly the console.log statement is executed i.e. The first part printing string “This is our first part”.

· Then the third part to print in console “This is our third part” .

· Then JavaScript waits for promise to get resolved and print the second part i.e. string “This will print after 3 seconds” with logic inside then() block when it gets the response after 3 seconds.

Lets look at the below similar code which is not using promise:-

You can notice in above example which is not using promise, that instead of waiting for returnValue variable to be assigned string value i.e. “This will print after 3 seconds” , JS simply prints value of the returnValue variable assigned initially i.e. null.

.catch()

We can use catch() to handle the promise in case of failure. So, the catch part will be executed if promise was rejected. As shown in example below:-

In above example we have added the logic to print a error message in catch part. This logic was executed because we have used reject in executor function of promise to indicate that it was unsuccessful.

--

--