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
Software Engineer | Software Architect | Blockchain Enthusiast
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.