Skip to curriculum
Jump to the editor

12.9. First result within a time limit, success or failure

Medium
Topics
15–25 min

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.

Signature

JAVASCRIPT
function firstWithin(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.

Requirements

  1. 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.
  2. Anything that settles after the first one is ignored.
  3. 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.
  4. Once an input wins, the time limit's timer is cleared, so no timer is left waiting. Each call has its own timer.
  5. Plain values count as already fulfilled, so they win even with ms 0. An already rejected promise wins against ms 0 too.
  6. No rejection is left unhandled, including rejections of inputs that lost.

Examples

JAVASCRIPT
const later = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

await firstWithin([later(300, "mirror A"), later(120, "mirror B")], 1000); // "mirror B", at 120 ms
JAVASCRIPT
await firstWithin([later(5000, "slow server")], 2000);
// rejects at 2000 ms: TimeoutError "Timed out after 2000 ms"
JAVASCRIPT
const failing = new Promise((_, reject) => setTimeout(() => reject(new Error("refused")), 50));

await firstWithin([later(300, "ok"), failing], 1000); // rejects with "refused" at 50 ms
JAVASCRIPT
await firstWithin(["cached"], 0); // "cached"

Environment

  • Plain JavaScript in a browser page; the tests call the global firstWithin from first-within.js.
  • The tests run on a virtual clock that replaces setTimeout and clearTimeout, so use those.
  • Cancelling the inputs that lost is out of scope: they keep running, and their results are ignored.
  • Promise.race is allowed, but the timer still has to be cleared.

Hints

  1. A promise can be resolved or rejected many times, but only the first call counts. How does that help here?
  2. The timer is one more contestant. What should happen to it when someone else wins?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…