Sign in
Log inSign up

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.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct