async / await: promises that read like prose
Mark a function async, await the value, and catch failures with plain try / catch.
Lesson 18 of 23 in JavaScript10 min1 exercise
async in front of a function does two things: it always returns a promise, and it unlocks await inside. await pauses the function until the promise settles — the rest of the page keeps running.
async function loadNames() {
const response = await fetch("https://api.example.com/users");
const users = await response.json();
return users.map((user) => user.name);
}
const names = await loadNames();Errors from awaited promises are thrown where you awaited them, so ordinary try / catch works. No .catch needed.
async function load() {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
console.error("load failed:", error.message);
return null;
}
}// slow: one after another
for (const id of ids) {
results.push(await load(id));
}
// fast: all at once
const results = await Promise.all(ids.map((id) => load(id)));Try it
Read a city's weather
main.js
console · output appears here
Exercises
Checked in your browser · hints and solutions included
01
Exercise
Weather, summarised
Write an async function weatherSummary(city) that:
- 01fetches
https://api.example.com/weather?city=<city> - 02returns
"Unknown city"when the response is not ok - 03otherwise returns a string like
"12°C in London"
Use await and a template literal.
exercise.js
console · run your code or check the answer