×

javascript · level 3 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Race a promise against the clock, or collect every outcome.

A server that never answers would freeze your app. Race the request against a , a promise that rejects after a set time, using . Whichever settles first wins, so a slow request fails cleanly instead of hanging forever.

When some requests may fail and you still want the rest, use . It waits for every one and gives back objects like { status: "fulfilled", value } for successes or { status: "rejected", reason } for failures. It never rejects, which makes it perfect for reports.

function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error(`No reply in ${ms}ms`)), ms);
  });
}
async function getJson(url) {
  const reply = await fetch(url);
  return reply.json();
}
try {
  const news = await Promise.race([getJson("https://api.example.com/news"), timeout(10)]);
  console.log(news.headline);
} catch (error) { console.log(error.message); }

The practice server takes about 40 milliseconds to answer, so try changing timeout(10) to timeout(500) and watch the headline win.