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?