How will you return the promise which will resolve earlier than others in an array of promises and cancel others which are pending?

Please find the code below:

const cacheSourceA = new Promise((resolve, reject) => {
    setTimeout(() => resolve({ someValue: 101 }), 1500);
});

const cacheSourceB = new Promise((resolve, reject) => {
    setTimeout(() => resolve({ someValue: 100 }), 200);
});

const cacheSourceC = new Promise((resolve, reject) => {
    setTimeout(() => resolve({ someValue: 102 }), 2000);
});


// create function getCachedValue
const getCachedValue = () => {

  // write your code here

};

getCachedValue();  // this should return the **cacheSourceB** because it's going to finish in just 200ms

Note: Check for errors also i.e. cacheSourceB is fast but it can return undefined in a real scenario.

Henrique Barcelos's photo

Promises are not cancellable. You can use Promise.race() to get the fastest one, but you can't prevent the others from being settled eventually. Their resolving/rejected values will eventually be freed up by the garbage collector, so this is not much of a problem.

Gyen Abubakar's photo

Use the static Promise.race() method. You pass an iterable object of Promises (usually an array of Promises) to it as a parameter. The Promise that settles first is returned.