Understanding Promises in JavaScript

Understanding Promises in JavaScript

Understanding Promises in JavaScript

Learn How Promises Really Work in JavaScript, to write better code.

JavaScript is a single-threaded programming language, that means only one thing can happen at a time. Before ES6, we used callbacks to handle asynchronous tasks such as network requests.

Using promises, we can avoid the infamous ‘callback hell’ and make our code cleaner, easier to read, and easier to understand.

Suppose we want to get some data from a server asynchronously, using callbacks we would do something like this:

getData(function(x){
console.log(x);
getMoreData(x, function(y){
console.log(y); 
getSomeMoreData(y, function(z){ 
console.log(z);
});
});
});

Here I am requesting some data from the server by calling the getData() function, which receives the data inside the callback function. Inside the callback function, I am requesting for some more data by calling the getMoreData() function passing the previously received data as an argument and so on.

This is what we call callback hell, where each callback is nested inside another callback, and each inner callback is dependent on its parent.

We can rewrite the above snippet using promises. For example:

getData()
  .then((x) => {
    console.log(x);
    return getMoreData(x);
  })
  .then((y) => {
    console.log(y);
    return getSomeMoreData(y);
  })
  .then((z) => {
    console.log(z);
   });

We can see that this is much cleaner and easier to understand than the callbacks example above it.

What is a Promise?

A Promise is an object that holds the future value of an async operation. For example, if we are requesting some data from a server, the promise promises us to get that data which we can use in future.

Before we get into all the technical stuff, let’s understand the terminology of a Promise.

States of a Promise

A Promise in JavaScript just like a promise in real-world has 3 states. It can be 1) unresolved (pending), 2) resolved (fulfilled), or 3) rejected. For example:

States of Promise

  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • *Resolved or Fulfilled *— A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • *Rejected *— A Promise is rejected if an error happened.

Now that we know what a Promise is, and Promise terminology, let’s get back to the practical side of the Promises.

Creating a Promise

Most of the times you will be consuming promises rather than creating them, but it’s still important to know how to create them.

Syntax:

const promise = new Promise((resolve, reject) => {
    ...
  });

We create a new promise using the Promise constructor it takes a single argument, a callback, also known as executor function which takes two callbacks, resolve and reject.

The executor function is immediately executed when a promise is created. The promise is resolved by calling the resolve() and rejected by calling reject(). For example:

const promise = new Promise((resolve, reject) => {
  if(allWentWell) {
    resolve('All things went well!');
  } else {
    reject('Something went wrong');
  }
});

The resolve() and reject() takes one argument which can be a string, number, boolean, array or object.

Let’s look at another example to fully understand the promise creation.

const promise = new Promise((resolve, reject) => {
  const randomNumber = Math.random();
  setTimeout(() => {
    if(randomNumber < .6) {
      resolve('All things went well!');
    } else {
    reject('Something went wrong');
  }
  }, 2000);
});

Here I am creating a new promise using the Promise constructor. The promise is resolved or rejected after 2 seconds of its creation. The promise is resolved if the randomNumber is less than .6 and rejected otherwise.

When the promise is created, it will be in the pending state, and its value will be undefined. For example:

Promise status pending

After the 2 seconds timer finishes, the promise is either resolved or rejected randomly, and its value will be the value passed to the resolve or reject function. For example:

Promise status resolved

Promise status rejected

*Note *— A promise can be resolved or rejected only once. Further invocation of resolve() or reject() has no effect on Promise state. For example:

const promise = new Promise((resolve, reject) => {
  resolve('Promise resolved');  // Promise is resolved
  reject('Promise rejected');   // Promise can't be rejected
});

Since resolve() is called first so the Promise will be resolved. Calling reject() after that will have no effect on the Promise state.

Consuming a Promise

Now that we know how to create a promise, let’s understand how to consume an already created promise. We consume a promise by calling then() and catch() methods on the promise.

For example, requesting data from an API using fetch which returns a promise.

.then() syntax: promise.then(successCallback, failureCallback)

The successCallback is called when a promise is resolved. It takes one argument which is the value passed to resolve().

The failureCallback is called when a promise is rejected. It takes one argument which is the value passed to reject().

For example:

const promise = new Promise((resolve, reject) => {
  const randomNumber = Math.random();

  if(randomNumber < .7) {
    resolve('All things went well!');
  } else {
    reject(new Error('Something went wrong'));
  }
});
promise.then((data) => {
  console.log(data);  // prints 'All things went well!'
  },
  (error) => {
  console.log(error); // prints Error object
  }
);

Here if the promise is resolved, the successCallback is called with the value passed to resolve(). And if the promise is rejected, the failureCallback is called with the value passed to reject().

.catch() syntax: promise.catch(failureCallback)

We use catch() for handling errors. It’s more readable than handling errors inside the failureCallback callback of the then() callback. For example:

const promise = new Promise((resolve, reject) => {
  reject(new Error('Something went wrong'));
});
promise
  .then((data) => {
     console.log(data);
   })
  .catch((error) => {
     console.log(error); // prints Error object
  });

Promise Chaining

The then() and catch() methods can also return a new promise which can be handled by chaining another then() at the end of the previous then() method.

We use promise chaining when we want to resolve promises in a sequence.

For example:

const promise1 = new Promise((resolve, reject) => {
  resolve('Promise1 resolved');
});
const promise2 = new Promise((resolve, reject) => {
  resolve('Promise2 resolved');
});
const promise3 = new Promise((resolve, reject) => {
  reject('Promise3 rejected');
});
promise1
  .then((data) => {
    console.log(data);  // Promise1 resolved
    return promise2;
  })
  .then((data) => {
    console.log(data);  // Promise2 resolved
    return promise3;
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);  // Promise3 rejected
  });

So what’s happening here?

  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • *Resolved or Fulfilled *— A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • *Rejected *— A Promise is rejected if an error happened.

Note — Generally only one catch() is enough for handling rejection of any promise in the promise chain, if it’s at the end of the chain.

Common Mistake

A lot of beginners make the mistake of nesting promises inside another promise. For example:

const promise1 = new Promise((resolve, reject) => {
  resolve('Promise1 resolved');
});
const promise2 = new Promise((resolve, reject) => {
  resolve('Promise2 resolved');
});
const promise3 = new Promise((resolve, reject) => {
  reject('Promise3 rejected');
});
promise1.then((data) => {
  console.log(data);  // Promise1 resolved
  promise2.then((data) => {
    console.log(data);  // Promise2 resolved

    promise3.then((data) => {
      console.log(data);
    }).catch((error) => {
      console.log(error);  // Promise3 rejected
    });
  }).catch((error) => {
    console.log(error);
  })
}).catch((error) => {
    console.log(error);
  });

Although this works fine, this is considered to be a poor style and makes our code difficult to read. If you have a sequence of promises to resolve, it’s better to chain promises one after another rather than nest one inside another.

Promise.all( )

This method takes an array of promises as input and returns a new promise that fulfills when all of the promises inside the input array have fulfilled or rejects as soon as one of the promises in the array rejects. For example:

const promise1 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve('Promise1 resolved');
 }, 2000);
});
const promise2 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve('Promise2 resolved');
 }, 1500);
});
Promise.all([promise1, promise2])
  .then((data) => console.log(data[0], data[1]))
  .catch((error) => console.log(error));
  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • *Resolved or Fulfilled *— A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • *Rejected *— A Promise is rejected if an error happened.
const promise1 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve('Promise1 resolved');
 }, 2000);
});
const promise2 = new Promise((resolve, reject) => {
 setTimeout(() => {
  reject('Promise2 rejected');
 }, 1500);
});
Promise.all([promise1, promise2])
  .then((data) => console.log(data[0], data[1]))
  .catch((error) => console.log(error));  // Promise2 rejected
  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • *Resolved or Fulfilled *— A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • *Rejected *— A Promise is rejected if an error happened.

This method can be useful when you have more than one promise, and you want to know when all of the promises have resolved. For example, if you are requesting data from different APIs and you want to do something with the data only when all of the requests are successful.

So Promise.all() waits for all promises to succeed and fails if any of the promises in the array fails.

Promise.race( )

This method takes an array of promises as input and returns a new promise that fulfills as soon as one of the promises in the input array fulfills or rejects as soon as one of the promises in the input array rejects. For example:

const promise1 = new Promise((resolve, reject) => {
 setTimeout(() => {
  resolve('Promise1 resolved');
 }, 1000);
});
const promise2 = new Promise((resolve, reject) => {
 setTimeout(() => {
  reject('Promise2 rejected');
 }, 1500);
});
Promise.race([promise1, promise2])
  .then((data) => console.log(data))  // Promise1 resolved
  .catch((error) => console.log(error));
  • Unresolved or Pending — A Promise is pending if the result is not ready. That is, it’s waiting for something to finish (for example, an async operation).
  • *Resolved or Fulfilled *— A Promise is resolved if the result is available. That is, something finished (for example, an async operation) and all went well.
  • *Rejected *— A Promise is rejected if an error happened.

So Promise.race() waits for one of the promises in the array to succeed or fail and fulfills or rejects as soon as one of the promises in the array is resolved or rejected.

Conclusion

We have learned what promises are and how to use them in JavaScript. A Promise has two parts 1) Promise creation and 2) consuming a Promise. Most of the times you will be consuming promises rather than creating them, but it’s still important to know how to create them.

That’s it and hope you found this article helpful! Please feel free to comment below and ask anything, suggest feedback or just chat. Cheers! ⭐️

javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.