/
Write
Start a team blog
NEW ✨
Start a team blog, invite your team, and start publishing.

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

Avi's photo
Avi
·Nov 27, 2019

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.