JavaScript Tutorial · Asynchronous JavaScript · Lesson 33 of 44
JavaScript Async/Await
Write asynchronous code that reads like synchronous code.
async functions
An async function always returns a promise. Inside it, await pauses until a promise settles and gives you its value — no .then() chains:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function loadProfile() {
console.log("loading...");
await wait(100);
return { name: "Ada", plan: "pro" };
}
const profile = await loadProfile();
console.log(profile);
Output
loading...
{ name: 'Ada', plan: 'pro' }Error handling
A rejected promise makes await throw, so use ordinary try...catch:
async function fetchPrice(symbol) {
if (symbol !== "ACME") throw new Error(`Unknown symbol ${symbol}`);
return 42;
}
async function main() {
try {
console.log(await fetchPrice("ACME"));
console.log(await fetchPrice("NOPE"));
} catch (err) {
console.log("Error:", err.message);
} finally {
console.log("finished");
}
}
await main();
Output
42 Error: Unknown symbol NOPE finished
Sequential vs parallel
await in a loop runs tasks one after another. When tasks are independent, start them all and await Promise.all(...) — much faster:
const task = (name, ms) => new Promise((resolve) => setTimeout(() => resolve(name), ms));
let start = Date.now();
for (const [name, ms] of [["a", 100], ["b", 100], ["c", 100]]) {
await task(name, ms);
}
console.log("sequential ≈", Math.round((Date.now() - start) / 100) * 100, "ms");
start = Date.now();
const results = await Promise.all([task("a", 100), task("b", 100), task("c", 100)]);
console.log(results, "parallel ≈", Math.round((Date.now() - start) / 100) * 100, "ms");
Output
sequential ≈ 300 ms [ 'a', 'b', 'c' ] parallel ≈ 100 ms
Practise async patterns: Map with concurrency limit and Retry with exponential backoff.
Test yourself
What does an async function always return?
A PromiseundefinedA callbackThe awaited value
Show answer
Answer: A Promise
Practice next
- Retry with Exponential Backoff · coding problem
- Run Async Tasks with a Concurrency Limit · coding problem