About me

I am a full stack .net developer with 5 years of experience in front-end and back-end technologies like HTML, CSS, Jquery, Angular, Typescript, Bootstrap, C#, MSSQL and Mongodb. I have done bachelor's in computer engineering from Gujarat Technological University. I have worked on web applications, Web APIs, Windows Forms, Web Forms, Tray applications and corporate websites. Programming is my hobby and I have starting writing blog to provide a platform for those who want to grow their career as a fullstack .NET developers.

Click here to know more about me

Promise in JavaScript

What is Promise?

The promise is a JavaScript class, objects of which promises eventual completion of some operations. The object of promise can be created as shown below:

let objPromise = new Promise((resolve, reject) => {});

JavaScript promises are not different than the promises we make in real life, either the promise is kept which corresponds to resolve in JavaScript or the promise is not kept which corresponds to reject in JavaScript. A promise object looks like that shown in the below image:

Promise object
Promise object
If you are not comfortable with arrow functions, I would suggest you go through JavaScript Arrow Functions

3 important methods that continue the code flow after promise resolve or reject

Below are the three methods that continue the flow or we can call them consumers of the promise object:

  1. then method - Contains the code block to execute after the promise is resolved
  2. catch method - Contains the code block to execute after the promise is rejected
  3. finally method - Contains the code block that needs to be executed irrespective to the promise being resolved or rejected

If we compile everything the promise will look like below image:

Promise with then, catch and finally
Promise with then, catch and finally

Use Case: If we need any variable for further execution of code

In the below example, I have added timeout of 100ms to call the method add(2, 3). Suppose there is a set of code that needs this answer to carry on further operations, we can do it in then method block as shown below. Here, I have displayed the value.

var add = (var1, var2) => {

  return parseInt(var1) + parseInt(var2);

};

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

  var ans;

  setTimeout(function() {

    ans = add(2, 3);

    if (typeof ans != undefined && !isNaN(ans)) {

      resolve(ans);

    } else {

      reject("failed");

    }

  }, 100);

});

objPromise.then((message) => {

  document.write(message);

});

objPromise.catch((message) => {

  document.write("Catch block " + message);

});

Try calling add(2, "") and check the output. Here is the JSFiddle link for your reference. I hope, you understood what JavaScript promise is. For any queries, you can write to me at info@beawesomewithprogramming.co.in. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.