
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.
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 theasynchronous operation
in which he is preparing vegetables without waiting for the pizza base.
INCIDENT C
Godfrey is talking about how he canreturn (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 asuccess
orfailure
.
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 resultapple cherry banana
not this.apple banana cherry
The reason for this to happen is that even thoughline 2
started earlier thanline 3
but the execution ofline2
takes 2 seconds whereasline3
takes 1 second, so it logged out in that manner.
CREATING A PROMISE.
Promise constructor takes in one argument ofcallback function
which contains two parametersresolve
andreject
.
Below is the method of creating a promise.
functionmaking_promise(mypromise){returnnewPromise((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 thattrue
tofalse
inside the if statement then we get to reject and we catch it by.catch(function)
.
functionmaking_promise(mypromise){returnnewPromise((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.
functioncreatepizza(pizza){returnnewPromise((resolve,reject)=>{console.log(`preparing to make${pizza}`);resolve();});}functionbringbase(){console.log("got pizza base from market");console.log("pizza created!")}createpizza("Margherita Pizza").then(bringbase);
console result:
preparing to make Margherita Pizzagot pizza base from marketpizza 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.
Top comments(2)

- Locationjhansi
- EducationIIT BHU Varanasi
- WorkIncoming software engineer at genpact
- Joined
Thanks
For further actions, you may consider blocking this person and/orreporting abuse