DEV Community

Cover image for How did promise evolve in Javascript?
Ankit Soni
Ankit Soni

Posted on • Updated on

How did promise evolve in Javascript?

Promise being one of the most important concepts of javascript is massively misunderstood by many developers, hence in this post firstly I will explain promise with a short story, and then we will dive deep in the code to understand it better.

Alt Text

INCIDENT A

Gilbert is making a request from Godfrey to make a promise of bringing pizza base from the market.

INCIDENT B

In this step, Gilbert is talking about the asynchronous operation in which he is preparing vegetables without waiting for the pizza base.

INCIDENT C

Godfrey is talking about how he can return (value) the promise which he is making. He is also trying to ask what if he fails in keeping up with the promise.

INCIDENT D & E

It shows that the response made by the promise can be a success or failure.

INCIDENT F

This is the final step where we receive the result of the promise.

DEFINING PROMISES IN JAVASCRIPT.

From this short story, we learn that promise is an object which is completed or failed by doing an asynchronous(not depending on the main operation) operation. Now we can attach callbacks to this promise object (which is a pizza base in our case) to perform functions on them.

HOW JAVASCRIPT WORKS.

Javascript is a single-threaded language by this I mean that it runs line by line and top to bottom, but what happens when it encounters an asynchronous function. Asynchronous function takes place in the order they complete. Let's see it in the following example.
Can you guess what will be logged out after we run it?

console.log("apple");
setTimeout(() => { console.log("banana") }, 2000);
setTimeout(() => { console.log("cherry") }, 1000);

console result apple cherry banana
not this apple banana cherry.

The reason for this to happen is that even though line 2 started earlier than line 3 but the execution of line2 takes 2 seconds whereas line3 takes 1 second, so it logged out in that manner.

CREATING A PROMISE.

Promise constructor takes in one argument of callback function which contains two parameters resolve and reject.

Below is the method of creating a promise.

function making_promise(mypromise)
{
    return new Promise((resolve, reject) => {
        if (true) {
            resolve();
        } else {
            reject();
        }
    });
}

Now once we have created a promise we will catch it by .then(function) when it is successful and by .catch(function) when it is failed.

In this manner.

making_promise("coding daily")
    .then(() => { console.log("promised completed successfully") })
    .catch(() => { console.log("it made an error") });

console result:

promised completed successfully

Now if I change that true to false inside the if statement then we get to reject and we catch it by .catch(function).

function making_promise(mypromise)
{
    return new Promise((resolve, reject) => {
        if (false) {
            resolve();
        } else {
            reject();
        }
    });
}
making_promise("coding daily")
    .then(() => { console.log("promised completed successfully") })
    .catch(() => { console.log("it made an error") });

console result:

it made an error

There are three states of response in Promise.

  • resolve: when the promise is successful.
  • reject: when there is an error.
  • pending: when the promise is pending.

CREATING PROMISE FOR OUR PIZZA EXAMPLE.

So we can make our pizza promise story in code like this.

function createpizza(pizza)
{
    return new Promise(( resolve , reject) => {
        console.log(`preparing to make ${pizza}`);
        resolve();
    });
}

function bringbase()
{
    console.log("got pizza base from market");
    console.log("pizza created!")
}

createpizza("Margherita Pizza").then(bringbase);

console result:

preparing to make Margherita Pizza
got pizza base from market
pizza created!

While doing web development we use a lot of asynchronous operations like getting JSON data from APIs, posting something to the website, deleting the data etc..

The best thing about asynchronous operations is that they do not hinder other processes occurring on the page which kind of makes the web faster and the overall experience of a user becomes good that's why it becomes important to learn asynchronous objects like Promises.

Go make your own promise.
Thank you!

I will also soon be publishing it on GeeksforGeeks.

Latest comments (2)

Collapse
 
bebhav profile image
bebhav

Engaging and useful Post. I have learnt something out of this.
Thanks and looking forward to see more posts like that.

Collapse
 
ankysony profile image
Ankit Soni

Thanks