An app can ask two mirrors for the same file and take whichever answers first, or ask one server and give up if it takes too long. Both ideas combine into one helper: settle like the first promise to settle, fulfilled or rejected, but never wait longer than a time limit. A request that hangs must not leave the page waiting forever.
Write firstWithin(promises, ms) in first-within.js.
functionfirstWithin(promises, ms) // returns a Promise
promises: an array of promises or plain values.
ms: the time limit in milliseconds.
On timeout, the promise rejects with an Error whose name is "TimeoutError" and whose message is Timed out after <ms> ms, for example Timed out after 200 ms.
Returns a promise that settles the same way as the first input to settle, at that moment: fulfilled with its value or rejected with its reason.
Anything that settles after the first one is ignored.
If nothing settles within ms, the promise rejects with the TimeoutError described above, exactly at ms and not earlier. An empty array always times out.
Once an input wins, the time limit's timer is cleared, so no timer is left waiting. Each call has its own timer.
Plain values count as already fulfilled, so they win even with ms 0. An already rejected promise wins against ms 0 too.
No rejection is left unhandled, including rejections of inputs that lost.
constlater= (ms, value) =>newPromise((resolve) =>setTimeout(() =>resolve(value), ms));awaitfirstWithin([later(300, "mirror A"), later(120, "mirror B")], 1000); // "mirror B", at 120 ms
JAVASCRIPT
awaitfirstWithin([later(5000, "slow server")], 2000);// rejects at 2000 ms: TimeoutError "Timed out after 2000 ms"
JAVASCRIPT
constfailing=newPromise((_, reject) =>setTimeout(() =>reject(newError("refused")), 50));awaitfirstWithin([later(300, "ok"), failing], 1000); // rejects with "refused" at 50 ms