The pizza is on its way
setTimeout, promises, async/await, try...catch, Promise.all, a timeout with Promise.race and cancelling with AbortController.
console.log("Ordered a pizza");
setTimeout(() => {
console.log("Ding-dong! The pizza is here");
}, 1000);
console.log("Sleeping while I wait");setTimeout doesn't stop the program: the callback fires later.JavaScript runs code on one thread. If it waited for the server's response, the page would freeze. So slow operations (network, timers, files) work asynchronously: the program moves on, and the result arrives later.
That "result later" is usually packed into a promise — an object that promises a value. A promise is pending, fulfilled (with a value) or rejected (with an error).
const pizza = new Promise((resolve) => {
setTimeout(() => resolve("Margherita"), 500);
});
pizza.then((name) => console.log("Delivered: " + name));
console.log("Promise created:", pizza instanceof Promise);resolve fulfils the promise with a value; then receives it when it's ready.Chains of then are awkward to read, so there's `async`/`await`. await pauses the function until the promise fulfils and gives its value. You can only write await inside an async function — and such a function always returns a promise itself.
function deliver(name, ms) {
return new Promise((resolve) => setTimeout(() => resolve(name), ms));
}
async function dinner() {
const pizza = await deliver("Pepperoni", 300);
console.log("Eating " + pizza);
}
dinner();A promise can also reject — the courier got lost. await turns a rejection into an ordinary error that try...catch catches.
function lostCourier() {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("The courier got lost")), 200);
});
}
async function dinner() {
try {
await lostCourier();
} catch (error) {
console.log("Dinner cancelled: " + error.message);
}
}
dinner();await = an error you can catch.Now, guests are coming. I ordered two pizzas from two different places. I could call the second place only after the first pizza arrives. Or I could call both at once and wait for both together.
The second way is what `Promise.all` is for: it takes an array of promises and fulfils with an array of their values once all of them are ready. The values come in the order of the original array, not in the order they arrived.
function cook(name, ms) {
return new Promise((resolve) => setTimeout(() => resolve(name), ms));
}
async function oneByOne() {
const start = Date.now();
await cook("Margherita", 100);
await cook("Pepperoni", 100);
console.log("One by one:", Date.now() - start, "ms");
}
async function together() {
const start = Date.now();
const pizzas = await Promise.all([cook("Margherita", 100), cook("Pepperoni", 100)]);
console.log("Together:", Date.now() - start, "ms", pizzas);
}
async function main() {
await oneByOne();
await together();
}
main();Why? In oneByOne, await cook(…) doesn't even let the second pizza start until the first is done. In together, both cook calls happen at once — both ovens are already heating — and await only waits for the slowest.
The rule: if the loads don't depend on each other, start them together. If the second needs the first one's result (find out the address, then deliver there), go one by one.
const ok = (name, ms) => new Promise((resolve) => setTimeout(() => resolve(name), ms));
const burnt = (ms) => new Promise((resolve, reject) => setTimeout(() => reject(new Error("the pizza burnt")), ms));
Promise.all([ok("Margherita", 50), burnt(20), ok("Pepperoni", 80)])
.then((pizzas) => console.log("all:", pizzas))
.catch((error) => console.log("all failed:", error.message));
Promise.allSettled([ok("Margherita", 50), burnt(20), ok("Pepperoni", 80)])
.then((results) => console.log("allSettled:", results.map((r) => r.status)));Promise.all; allSettled reports on each one honestly.Sometimes the courier isn't lost — just very, very slow. You can't wait forever: the user stares at a spinning spinner and leaves. You need a timeout.
That's what `Promise.race` is for: it fulfils (or rejects) the same way as the first promise to finish. So we race the courier against an alarm clock that rejects with an error after N milliseconds.
function courier(ms) {
return new Promise((resolve) => setTimeout(() => resolve("pizza"), ms));
}
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("waited " + ms + " ms, that's enough")), ms);
});
}
async function dinner(courierMs) {
try {
const food = await Promise.race([courier(courierMs), timeout(150)]);
console.log("Dinner: " + food);
} catch (error) {
console.log("Dinner cancelled: " + error.message);
}
}
dinner(50);
dinner(300);Notice that the losing courier still arrives — race doesn't stop him, it just stops listening. To really cancel an operation there's `AbortController`. It has a signal — you hand it to whoever does the work — and an abort() method that fires that signal.
const controller = new AbortController();
function deliver(signal) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve("pizza"), 300);
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(new Error("order cancelled"));
});
});
}
deliver(controller.signal)
.then((food) => console.log("Delivered: " + food))
.catch((error) => console.log("The courier turned back: " + error.message));
setTimeout(() => controller.abort(), 100);In real life you pass the signal to fetch(url, { signal }), and the browser drops the request itself. That's how a search box cancels the old request when you type the next letter, and how a page stops a download the user has already navigated away from.
Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.