Understanding Promise in JavaScript

Understanding Promise in JavaScript

Introduction

Promises in JavaScript are a comparatively new feature that allow you to defer further actions until after a previous action has completed, or respond to its failure.

Promise in JavaScript is a constructor function that is used to do something asynchronously. When the task is complete is either you fulfill the promise or fail to do so. It takes a call back function as it’s argument with two parameters (reject and resolve). The two parameters determine the outcome of the promise.

Application of JavaScript Promise

  • Promises are used for asynchronous handling of events.
  • Promises are used for handling asynchronous http requests.

The syntax of the JavaScript promise is:

let makeServerRequest = new Promise ((resolve, reject) => {

});

In the code above, we declare a variable makeServerRequest and set it to a new Promise which contains a call back function as its argument. The call back function also has two parameters (resolve and reject).

A promise usually has three states:

  1. Pending
  2. Resolve
  3. Reject
  • Pending is when the promise is in its initial state, neither fulfilled nor rejected. Just like the code in the previous example.
  • Resolve means the operation was completed.
  • Reject means the operation failed.

Another Promise diagram.png

To make our promise in the previous code pass the pending state we need to add a way to complete the promise.

let makeServerRequest = new Promise ((resolve, reject) => {
    let a = 2 + 3;
    if (a == 5){
        resolve ("Successful");
    } else {
        reject ("Failed")
    }
});

In the code above the variable a is assigned a value 5, so the output will be successful. Otherwise the output will be failed.

When you have a process that takes an unknown amount of time, like a server request, which takes an amount of time, and after the process you want to do something with the response from the server, this can be achieved by using the then method. The then method is executed after your promise is fulfilled. This is an example based on the previous code.

let makeServerRequest = new Promise ((resolve, reject) => {
    let a = 2 + 3;
    if (a == 5){
        resolve ("Successful");
    } else {
        reject ("Failed")
    }
});

makeServerRequest.then (result => {
    console.log(result);
});

The catch method is used when your promise has been rejected. It is executed immediately after a promised rejected method is called. This is an example based on the previous code.

let makeServerRequest = new Promise ((resolve, reject) => {
    let a = 2 + 3;
    if (a == 5){
        resolve ("Successful");
    } else {
        reject ("Failed")
    }
});

makeServerRequest.then (result => {
    console.log(result);
});

makeServerRequest.catch (result => {
    console.log(error);
});

In the code above the process is successful, it will log the result, and incase if it fails it will log error.

Summary

  1. A promise constructor takes only one argument (a callback function)
  2. The callback function takes two arguments (resolve and reject)
  3. A promise performs operations inside the callback function and if everything went well it then calls resolve.
  4. If the desired operation performed by the promise does not go well then it calls reject.
  5. The then() method is invoked when a promise is either resolved or rejected.
  6. The catch() method is invoked when a promise is either rejected or error has occurred in execution.

Don’t only read, Code it yourself.