Let’s say I have async functions calling external APIs with variable response times defined as below:
async function promise1() { /* API Call */ }
async function promise2() { /* API Call */ }
async function promise3() { /* API Call */ }
// ... up to promiseN
If I wanted to run them all in parallel and wait for all of them to resolve, I would run them like result = Promise.all([promise1, promise2, promise3,...,promiseN])
.
However, I have a slightly different requirement:
- I want to start all the promises in parallel.
- As soon as the first one resolves (whichever that is), I want to wait 500 milliseconds for the other promises to resolve.
- After that 500 ms window, I want to ignore any remaining unresolved promises.
result
should contain all the promises that resolved by the time the 500 ms window ends.
So for example, if promise2
resolves first at time T
, I want to wait until T + 500
ms for the others to resolve. Any promises that haven’t resolved by then should be ignored.
How can I accomplish this in JavaScript?
2
Answers
Instead of
Promise.all
you will needPromise.any
(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/any) and chain a.then()
, incapsulating your 500ms wait into a second promise, which, when fulfilled, so 500ms passed after the first promise fulfilled, loop your promises and reject those which were not fulfilled yet.You could await for the first promise to settle with
Promise.race
. Then create a timeout promise (that rejects after 5 seconds), and let each of the promises race with that timeout promise. Await the results withPromise.allSettled
.Here is a demo: