JavaScript Promise Example | JavaScript Promises | Promise.all() | Promise.race()

In JavaScript we uses promises for handling async API calls.  In JavaScript the  Promise takes one argument as a callback containing 2 parameters resolve and reject.

If promise is fulfilled the resolve function will be called and if promise is not fulfilled  reject function will be called.

Let me explain with some example:

Here in this example I have defined 2 promises one is classResult and other is gotMedal. classResult and gotMedal returns promises. If promise resolved then code block executes else catch code block executes.

Here in this example both promises are executing independently. But there might be a case if second API request need to send some parameters of first API call response this means second promise will wait until first promise returns the response. Below is the example of dependent promises:

Here int this example if student obtained marks are greater than or equal to 80 then we resolve the promise and execute the gotMedal promise. If student is topper then we execute the meetPresident promise. So here all 3 promises are dependent to each other.

There might be a case when all these 3 promises are independent then we can execute these all promises by Promise.all().

Promise.all() executes all 3 function asynchronously and you will execute the then callback once all the requests are resolved else catch block will be executed.

Now there might be case that you have 6 API calls but once you got response any one of them then you don't wanted to wait for others.

We use Promise.race() for this. For example you have similar data on 3 servers and you you send all 3 request to each server once you get response from any one server you will not love to wait for others 2 servers response.


Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *