Promises in JavaScript

ayush65

ayush65

Posted on July 21, 2022

Promises in JavaScript

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);
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

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);
   });
Enter fullscreen mode Exit fullscreen mode

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.

States of a Promise

A Promise in JavaScript just like a promise in real-world has 3 states. It can be pending, resolved , rejected. For example:

MarineGEO circle logo

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

💖 💪 🙅 🚩
ayush65
ayush65

Posted on July 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related