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.

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.

Suggestion: When build an app in JavaScript, you often have to rewrite the same components and pieces. Instead, share them as Bit components so you can later use, share and sync them in all your projects. Create a collection:

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:

  • 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:

javascript "javascript")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:

*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()** syntaxpromise.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()** syntaxpromise.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! ⭐️

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Java vs. JavaScript: Know The Difference

Java vs. JavaScript: Know the Difference, Java vs. JavaScript: What's the Difference? Java vs. JavaScript: Major Similarities and Differences. pros and cons of JavaScript and Java.