JavaScript

Promises in JavaScript | Explained

JavaScript is a high-level programming language where code is executed line by line which means that the next line of code is only executed once the previous line of code is completely executed. To solve this problem, JavaScript offers callback functions that are asynchronous equivalent to a function.

Asynchronous code is executed immediately and unlike synchronous code, it does not wait for the previous line of code to finish executing. However, when we are dealing with multiple asynchronous operations, using callbacks is not a good choice as the code becomes confusing, unmanageable, and difficult to understand or debug. Hence the solution is to use Promises.

In this post, we will go through the concept of Promises in javaScript along with examples.

What are Promises?

A promise is an operation or task that will be completed in the future. Promise syntax is given below:

Promise Syntax:

let myPromise = new Promise(function(resolve, reject){

// code

});

As we can see from the above-given syntax of Promise, the promise constructor takes only the callback function as an argument. In the callback function, we have the resolve and reject arguments where resolve is called when the operations performed inside the callback function are successful. However, if the operation is unsuccessful then call reject.

To put it simply let us suppose that your birthday is coming up and your mother promises you to get you a new laptop. You haven’t received the laptop and you cannot be really sure whether you’ll get the laptop or not until your birthday. Your mother might buy you a laptop or she can change her mind and buy you something else. This is a promise in layman language.

Every promise has three states or possibilities:

  • Pending: You are not sure whether you will get the laptop or not; undefined.
  • Fulfilled: Your mother buys you the laptop; result value.
  • Rejected: Your mother doesn’t buy you a laptop; error object.

Advantages of Promises

  • Asynchronous operations are handled in a simpler way
  • Code readability is improved hence debugging becomes easy
  • Error handling is easier than events or callbacks.
  • The flow of control is better defined by asynchronous code.

Before going to the Promise examples, let us go through another concept within promises that are promise consumers whose function is to consume Promises by registering functions using:

  • .then(): When a promise is resolved or rejected, this method is called.
  • .catch(): When a promise is rejected or an error occurs during the promise’s execution, this method is called.

Example:

In this example, we will check whether two numbers are equal or not using promises, and based on whether this operation is successful or not, we will display output.

// Promise initializing
// Promise initializing
varmyPromise = newPromise(function(resolve, reject) {
const num1 = 4;
const num2 = 4;
// compare two numbers
if(num1 === num2) {
// when operation is successful
    resolve();
  } else {
// when error comes
    reject();
  }
});

// Promise Consumers
myPromise.
    then(function () {
console.log("Operation Successful");
    }).
    catch(function () {
console.log('Error Occurred');
    });
  • We initialized the Promise with the name myPromise and provided a callback function.
  • In the function, we created the two numbers that we want to compare
  • We used the if-else statement to see if the numbers are equal or not
  • And then we included the promise consumers
  • If promise operation is successful then .then consumer will be invoked and the console will display Operation Successful
  • If a promise is not successful then you will see a message that says “error occurred” on the console

Since the operation was successful, we see Operation Successful in the console log.

Let us now change the numbers initialized in the call-back function to see whether the catch function detects an error or not.

// Promise initializing
varmyPromise = newPromise(function(resolve, reject) {
const num1 = 5;
const num2 = 4;
// compare two numbers
if(num1 === num2) {
// when operation is successful
    resolve();
  } else {
// when error comes
    reject();
  }
});

// Promise Consumers
myPromise.
    then(function () {
console.log("Operation Successful");
    }).
    catch(function () {
console.log('Error Occurred');
    });

Since the numbers are not equal now, the reject() function will be invoked and the error will be cached by the catch function:

Conclusion

A promise is an operation that is completed in the future and helps developers to implement asynchronous code. Promises are preferred over callback functions as promises are much more cleaner hence improving readability, and debugging of the code, it has better error handling as well as multiple asynchronous operations are better handled with promises. A promise can be fulfilled, rejected or it is pending.

In this post, we went through Promises in JavaScript and explained Promises with the help of an example.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.