Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
10

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.

  1. Pending: The initial state. The operation isn't finished.
  2. Fulfilled: The operation completed successfully. The promise now has a resolved value.
  3. Rejected: The operation failed. The promise has a reason, which is typically an Error object.

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 async function without await. If you forget await, 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 a Promise object 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.

Try a free mock interviewPractice system design problems
Previous

Event Loop: Call Stack, Task and Microtask Queues

Next

Web Workers: Multi-threading in the Browser