Promise.race() in javascript

Promise.race():  Yes, there exists a function called Promise.race() ,if you have never heard of or never used it before, lets try to understand what Promise.race() actually is ?

   Promise.race() accepts a iterable Promises and returns a new Promise which resolves as soon as one of the Promises passed to it resolves. The returned Promise will contain a value for the first Promise that got resolved. Lets understand it thorough few examples.

Example 1 :

var promise1 = Promise.resolve('a');
var promise2 = Promise.resolve('b');
var resolvedPromise = Promise.race([promise1,promise2]);
resolvedPromise.then((data) => {
  console.log('Resolved Promise data: ', data); // This prints ['a'];
});

In the above code promise1 resolved first and hence the resultant promise has value a passed to it. Its used during race conditions where any one of the promises resolves then return it.

Example 2 :

var promise1 = new Promise(function(resolve, reject) { 
                 setTimeout(resolve, 500, 'a');
              });
var promise2 = new Promise(function(resolve, reject) { 
               setTimeout(resolve, 800, 'b');
   });
var resolvedPromise = Promise.race([promise1,promise2]);
resolvedPromise.then((data) => {
  console.log('Resolved Promise data: ', data); // This prints ['a'];
});

In the above example the promise 1 and promise 2 resolves after setTimeout asynchronously. Hence, based on the time promise1 resolves first because of the 500ms compared to promise2 which resolves after 800ms. Therefore the Promise.race() will give back a promise that will contain data of promise1 i.e value 'a'. 

Now, you know how to use Promise.race() function use it wisely :).

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s