Async / Await
async functions, await, try/catch
Skills taught: js.async-await, js.error-handling, js.async
async and await basics
// async keyword makes the function return a Promise
async function getUser(id) {
// await pauses here until the promise resolves
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user; // returned value is wrapped in a resolved Promise
}
// Call the async function
getUser(1).then(user => console.log(user));
// Or await it inside another async function
async function displayUser() {
const user = await getUser(1);
document.querySelector('#name').textContent = user.name;
}
Error handling with try/catch
async function loadUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
// HTTP errors don't throw — check manually
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const user = await response.json();
return user;
} catch (error) {
// Network errors OR the thrown error above
console.error('Failed to load user:', error.message);
return null; // graceful fallback
} finally {
// Runs always — hide loading spinner here
hideSpinner();
}
}
Parallel vs sequential
// SEQUENTIAL — each request waits for the previous (slow: 3×delay)
async function sequential() {
const user = await fetchUser(); // 1 second
const posts = await fetchPosts(); // 1 second
const comments = await fetchComments(); // 1 second
// Total: ~3 seconds
return { user, posts, comments };
}
// PARALLEL — all requests fire at the same time (fast: 1×max_delay)
async function parallel() {
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments(),
]);
// Total: ~1 second (whichever is slowest)
return { user, posts, comments };
}
// async in a for loop — sequential (intentional: each depends on previous)
async function processItems(items) {
for (const item of items) {
await processItem(item); // waits for each before the next
}
}
Warning: Do NOT use async inside forEach — it doesn't await the callbacks. Use for...of instead: for (const item of items) { await process(item); }
Frequently Asked Questions
Can I use await outside an async function?
In ES modules (type='module'), top-level await is supported. In classic scripts, you need to wrap code in an async IIFE: (async () => { const data = await fetch(...); })().
Does await block the entire browser?
No. await only suspends the current async function — other code, event listeners, and rendering continue normally. JavaScript is still single-threaded, but await yields control back to the event loop.