javascript · level 3 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Three checks, one failure. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function check(name) {
await wait(50);
if (name === "") { throw new Error("blank name"); }
return name.toUpperCase();
}
const outcomes = await Promise.allSettled([check("ok"), check(""), check("go")]);
console.log(outcomes.map((o) => o.status));
console.log(outcomes[1].reason.message, outcomes[2].value);
your turn
Your turn. Set a fair time limit.
The practice server takes about 40 milliseconds to reply. Give the request a time limit of a few hundred milliseconds, so the score wins the race.
fix it
One missing room ruins the report. Can you fix it?
- The practice server has no room called zzz. What does
Promise.alldo when one request fails? Promise.allrejects as soon as one fails, so the report never runs. The loop also expectsstatusobjects.- On line 7, change
Promise.alltoPromise.allSettled, then press run.
nailed it
you can race the clock and report on it all. :D
Promise.racesettles with whichever promise finishes first.- Race a request against a timeout so nothing hangs forever.
Promise.allSettledreports every outcome and never rejects.
new words in your collection
- timeout
- Promise.race
- Promise.allSettled
This lesson isn’t saved. A free account remembers every lesson you finish.