Async/await is syntactic sugar over Promises. It makes async code look and feel like synchronous code. This is the modern way to handle async operations in Node.js.
Basic Syntax
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
}
// Call it
const user = await getUser(1);
console.log(user);
The async keyword before the function means it returns a Promise. The await keyword pauses execution until the Promise resolves.
Error Handling with Try/Catch
async function fetchData() {
try {
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Fetch failed:", error);
throw error; // Re-throw if caller needs to handle it
}
}
Try it Yourself โ
Parallel Async Operations
// Sequential (slow)
const users = await fetchUsers();
const posts = await fetchPosts();
// Parallel (fast)
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts()
]);
Async Iteration
// Process items one at a time
async function processAll(items) {
for (const item of items) {
await processItem(item);
}
}
// Process items in parallel
async function processAllParallel(items) {
await Promise.all(items.map(item => processItem(item)));
}
Rule of Thumb: Use await when you need the result before moving on. Use Promise.all() when operations are independent and can run in parallel.