Javascript - Collection Promise.race()

Introduction

To get the results of the first promise in the array of promise, use Promise.race().

Promise.race() takes an array of promises.

It will fulfill its returned promise as soon as the first promise in that array fulfills.

To fetch some JSON data with timeout and default value

// A Promise that times out after given time (t) 
function delay(t) { 
       return new Promise((resolve, reject) => { 
              setTimeout(resolve, t); 
       }); 
} 
// Whichever Promise fulfills first is the result passed to our handler 
Promise.race([ 
       fetchData(), 
       delay(5000).then(() => { data: "test" }) 
]) 
.then((res) => { 
        // this will be "test" if fetchData() takes longer than 5 sec. 
        console.log("data:", res.data); 
}) 
.catch(function(err) { 
       console.log("error:", err); 
}); 

Here, the delay() function returns a new promise that resolves after t milliseconds.

We attach a handler to that returned promise to return our default user object {user: "guest"}.

It ensures that if we get user data from our server within 5 seconds, we will get the user details; otherwise a guest user will be used.

Related Topic