async/await
10 min read
async/await
async/await is syntax sugar over Promises. It lets you write asynchronous code that reads like synchronous code. An async function always returns a Promise. await pauses execution inside the function until the awaited Promise settles.
javascript
async function fetchUser(id) {
const res = await fetch("/api/users/" + id);
const data = await res.json();
return data;
}
fetchUser(1).then(user => console.log(user));Error Handling with try/catch
javascript
async function loadData(url) {
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error("HTTP " + res.status);
}
return await res.json();
} catch (err) {
console.error("Failed to load:", err.message);
return null;
} finally {
console.log("Request finished");
}
}Parallel vs Sequential
javascript
// Sequential — total time = A + B
async function sequential() {
const a = await fetchUser(1);
const b = await fetchUser(2);
return [a, b];
}
// Parallel — total time = max(A, B)
async function parallel() {
const [a, b] = await Promise.all([
fetchUser(1),
fetchUser(2)
]);
return [a, b];
}Avoid await inside loops (for + await). This creates sequential requests. Collect your Promises into an array and use Promise.all() to run them concurrently.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises