Why some code has to wait
Run this and look at the order of the lines it prints:
console.log("1. Order a pizza");
setTimeout(() => console.log("3. Pizza arrives"), 1000);
console.log("2. Set the table while waiting");
setTimeout schedules work for later and returns straight away, so line 2 prints before line 3. If JavaScript froze while waiting, the whole page would stop responding to clicks. Network requests and file reads work the same way.
Promises
A promise is an object that stands for a result that will arrive later. It is either pending, fulfilled (it has a value) or rejected (it has an error). Here is a function that returns a promise which fulfils after a delay:
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
wait(500).then(() => console.log("Half a second later"));
console.log("This prints first");
.then() runs a function when the promise is fulfilled. Chaining many .then() calls gets hard to read, which is why async and await were added.
async and await
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function makeTea() {
console.log("Boil water");
await wait(300);
console.log("Add tea bag");
await wait(200);
console.log("Tea is ready");
return "green tea";
}
makeTea().then(tea => console.log("Enjoy your", tea));
asyncbefore a function means it always returns a promise.awaitpauses that function until the promise settles, then gives you its value. The rest of the page keeps working meanwhile.- You can only use
awaitinside anasyncfunction (or at the top level of a module).
Handling errors
When an awaited promise is rejected, await throws the error, so you handle it with an ordinary try and catch:
function checkAnswer(answer) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (answer === 42) resolve("Correct!");
else reject(new Error("Wrong answer: " + answer));
}, 100);
});
}
async function quiz() {
for (const guess of [7, 42]) {
try {
console.log(await checkAnswer(guess));
} catch (error) {
console.log("Problem:", error.message);
}
}
}
quiz();
A rejected promise that nobody catches shows up as an "Uncaught (in promise)" error in the console. Always catch errors where you can show the user a helpful message.
Waiting for several things at once
Awaiting tasks one by one adds up their times. If they do not depend on each other, start them all and wait for all of them with Promise.all:
function load(name, ms) {
return new Promise(resolve => setTimeout(() => resolve(name + " loaded"), ms));
}
async function main() {
const start = Date.now();
const results = await Promise.all([
load("lessons", 300),
load("quizzes", 200),
load("profile", 100),
]);
console.log(results);
console.log("Took about", Math.round((Date.now() - start) / 100) * 100, "ms, not 600");
}
main();
The results come back in the same order as the list, whichever finished first. If any one of them fails, Promise.all rejects; use Promise.allSettled when you want every result, including failures.
Try it yourself
In Unays Code, write an async countdown that prints 3, 2, 1 and "Go!" one second apart using wait. Then use what you learned with real data in loading data with fetch.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].