Sitemap
The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

JavaScript Promises

2 min readJul 12, 2020

--

JavaScript promises are just similar to the promises that we do in our real life, but javaScript keep up promises😜.

Without taking much time, lets get into some examples:

Simple Example:

Press enter or click to view image in full size

In the above example, we can clearly see that .then() is triggered when a promise is resolved and .catch() is triggered when a promise is rejected.

Now let’s see a realtime example,

We are going to have 3 functions,
1. cleanRoom
2. removeGarbage
3. getIcecreamAsReward

As the functions names suggests, its a sequence of activities.
We are going to have setTimeout in each of these functions to get a better understanding when to reach the Promises part. The use of setTimeout function can be related with the response time of a REST api request.

The functions without promise are:

Press enter or click to view image in full size

And the output will be,

won ice cream as a reward
garbage removed
room cleaned

The ouput is not in correct executed order. The reason for the incorrect order is the setTimeout function. consider each setTimeout as a fetch api call where multiple fetch calls will recieve response at different order.

Get saravana kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

This type of scenario is where the Promise becomes the saviour.

Lets us see the same 3 functions which returns a Promise each,

Press enter or click to view image in full size

Now the output will be,

room cleaned, garbage removed, won ice cream as a reward

The difference between two approaches is that,
1. In the second approach we have returned a promise instead of printing the result in the function itself
2. Instead of calling the functions independently, we have nested the function calls.
3. We have passed the response of previous function’s return value to the next function

Promise.all() :

If we have a situation like we want all the promises to be executed in correct order, but in parallel, then we can use the Promise.all() concept

Syntax:
Promise.all(<array of promises>)
.then(function(<array of responses in same order>){})

Promise.race() :

Promise.race() is the feature which executes the .then() part when atleast one of the promises gets resolved or rejected.

Syntax:
Promise.race(<array of promises>)
.then(function(<response of first promise which gets resolved/rejected>){})

The difference between all() and race() is that .then() part of all() gets executed when all the promises are resolved/rejected, while the .then() part of race() gets executed atleast when one promise gets resolved/rejected.

--

--

The Startup

Published in The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.