Frontend System Design · Lesson 10 of 86 · 4 min
Async JavaScript: Promises and async/await
This is how you explain non-blocking operations and justify your choice of concurrency patterns in an interview.
After the last lesson on the Event Loop, you know why JavaScript needs to handle tasks asynchronously. Now you'll learn how. Promises and async/await are the modern tools for managing operations like network requests without freezing the main thread. Mastering them is non-negotiable for any frontend role.
How to model an async operation with a Promise
A Promise is an object that represents the eventual result of an asynchronous operation. Think of it as a placeholder for a value you don't have yet. It's a state machine that can be in one of three states.
- Pending: The initial state. The operation isn't finished.
- Fulfilled: The operation completed successfully. The promise now has a resolved value.
- Rejected: The operation failed. The promise has a reason, which is typically an
Errorobject.
A promise is settled when it is either fulfilled or rejected. This transition only happens once.
You interact with a settled promise using its methods. .then() runs a callback when the promise is fulfilled, and .catch() runs one when it's rejected. Since these methods return a new promise, you can chain them to orchestrate a sequence of asynchronous steps.
Writing readable async code with async/await
async/await is syntactic sugar built on top of Promises. It lets you write asynchronous code that looks and reads like synchronous code, which is a huge win for clarity and maintenance.
An async function always returns a promise. Inside an async function, you can use the await keyword. await pauses the execution of the async function only until a promise settles. While your function is paused, the JavaScript engine is free to run other code, keeping the event loop and your UI responsive.
When the promise settles, await unwraps the value. If the promise was fulfilled, it returns the value. If it was rejected, it throws the error. This allows you to use standard try...catch blocks for error handling, which is often cleaner than long .catch() chains.
The trap: A common mistake is calling a promise-returning function inside an
asyncfunction withoutawait. If you forgetawait, you don't get the resolved value. You get the promise object itself, which is almost never what you want. Your code will continue executing immediately, likely leading to race conditions or errors from using aPromiseobject where a value was expected.
How to handle multiple requests efficiently
In a system design interview, you'll be asked how to fetch data from multiple sources. A naive approach is to await requests one by one.
// Sequential (slow)
const user = await fetch('/api/user/1');
const posts = await fetch('/api/posts/1');
const comments = await fetch('/api/comments/1');
This is a waterfall. Each request only starts after the previous one completes. If the requests are independent, you're wasting time. The correct pattern is to run them concurrently with Promise.all.
Promise.all takes an array of promises and returns a single promise that fulfills with an array of the results. The requests are fired off in parallel. This is significantly faster.
async function getUserPageData(userId) {
try {
// These requests are independent, so run them in parallel.
const [userResponse, postsResponse] = await Promise.all([
fetch(`/api/users/${userId}`),
fetch(`/api/users/${userId}/posts`)
]);
// Promise.all rejects if any fetch fails. Check responses individually.
if (!userResponse.ok) {
throw new Error(`Failed to fetch user: ${userResponse.status}`);
}
if (!postsResponse.ok) {
throw new Error(`Failed to fetch posts: ${postsResponse.status}`);
}
// .json() also returns a promise, so we can use Promise.all again.
const [user, posts] = await Promise.all([
userResponse.json(),
postsResponse.json()
]);
return { user, posts };
} catch (error) {
console.error('Error fetching user page data:', error);
// In a real app, you'd update the UI to show an error state.
throw error; // Re-throw to allow the caller to handle it.
}
}
The trade-off: Promise.all is fail-fast. If any single promise in the array rejects, the entire Promise.all immediately rejects, and you lose the results of any other promises that might have succeeded.
If you need to know the outcome of every promise, even if some fail, use Promise.allSettled. It waits for all promises to settle and returns an array of objects describing the outcome of each one ({status: 'fulfilled', value: ...} or {status: 'rejected', reason: ...}). This is useful for situations where partial data is better than no data.
When to use Promise.race
Promise.race is less common but has specific uses. It takes an array of promises and settles as soon as the first promise in the array settles (either fulfills or rejects).
A classic use case is implementing a timeout for a network request. You race the fetch promise against a setTimeout promise. If the timeout finishes first, you can abort the request or handle the timeout error. This demonstrates control over asynchronous flows, a valuable skill to show in an interview.
function timeout(ms) {
return new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timed out')), ms)
);
}
async function fetchWithTimeout(url, options, ms = 5000) {
return Promise.race([
fetch(url, options),
timeout(ms)
]);
}
Try it
Write an async function fetchWithRetry(url, maxRetries) that fetches data from a URL. If the fetch call fails (e.g., network error), it should retry the request up to maxRetries times with a short delay between retries. If it succeeds, it should return the response. If it fails after all retries, it should throw the last error it received.
Next: We'll take concurrency a step further and learn how to run code off the main thread with Web Workers: Multi-threading in the Browser.
Lock it in — apply this lesson under interview conditions.