Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
JavaScript for Frontend Interviews
  1. 1.Introduction to JavaScript & Setup
  2. 2.Variables and Data Types
  3. 3.Operators and Expressions
  4. 4.Control Flow: Conditionals
  5. 5.Control Flow: Loops
  6. 6.Functions: Basics
  7. 7.Arrays and Objects
  8. 8.Higher-Order Functions & Callbacks
  9. 9.Scope and Closures
  10. 10.`this` Keyword and Context
  11. 11.Asynchronous JavaScript: Callbacks & Promises
  12. 12.ES6+ Features (Part 1)
  13. 13.ES6+ Features (Part 2)
  14. 14.Error Handling & Debugging
  15. 15.Asynchronous JavaScript: Async/Await
  16. 16.Prototypal Inheritance & `new` Keyword
  17. 17.Event Loop, Microtasks & Macrotasks
  18. 18.Working with the DOM
  19. 19.Advanced Array Methods & Data Structures
  20. 20.Frontend Interview Prep & Best Practices
JavaScript for Frontend Interviews
15

JavaScript · Lesson 15 of 20 · 3 min

Asynchronous JavaScript: Async/Await

This is how you write clean, sequential-looking asynchronous code and explain its non-blocking nature under pressure.

Write asynchronous code that reads like synchronous code

async/await exists for one primary reason: readability. It lets you handle promise-based operations without chaining .then() callbacks, making the logic appear as a simple, top-to-bottom script.

An async function always returns a promise. Inside it, you can use the await keyword. await pauses the execution of the async function until a promise settles. If the promise resolves, await returns the resolved value. If it rejects, it throws an error.

This means error handling uses the standard try...catch block you already know, which is often cleaner than a separate .catch() chain.

async function fetchTodo(id) {
  try {
    const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);

    if (!response.ok) {
      // Handle HTTP errors like 404 or 500
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    console.log(data.title);
    return data;
  } catch (error) {
    // Handle network errors or the error thrown above
    console.error(`Could not fetch todo ${id}:`, error.message);
    // Depending on the use case, you might return null, an empty object,
    // or re-throw a more specific error.
    return null;
  }
}

fetchTodo(1);

In an interview, writing code like this demonstrates you can handle both the happy path and the error states cleanly.

Avoid sequential awaits for independent tasks

The trap: A common mistake is awaiting promises one by one when they don't depend on each other. This creates an unnecessary waterfall, where the total time is the sum of all operations.

If you need to fetch two independent pieces of data, don't do this:

// Inefficient: Fetches user, then waits, then fetches posts.
async function getInitialData(userId) {
  const user = await fetch(`/api/users/${userId}`); // e.g., takes 200ms
  const posts = await fetch(`/api/posts?userId=${userId}`); // e.g., takes 300ms
  // Total time: ~500ms
}

The second fetch doesn't start until the first one is completely finished.

Instead, start all the promises at once and wait for them together with Promise.all. This runs the operations concurrently. The total time is determined by the slowest promise, not the sum of all of them.

// Efficient: Fetches user and posts at the same time.
async function getInitialData(userId) {
  const [userResponse, postsResponse] = await Promise.all([
    fetch(`/api/users/${userId}`), // starts at 0ms
    fetch(`/api/posts?userId=${userId}`) // starts at 0ms
  ]);
  // Total time: ~300ms (the longer of the two)
}

Recognizing when to use Promise.all is a strong signal that you think about performance.

Explain how await is non-blocking

An interviewer might ask: "If await pauses the function, doesn't that block the browser?"

No. It's crucial to clarify that await only pauses the execution of the async function it's in. It does not block the main thread.

When an async function hits an await, it yields control back to the event loop. The JavaScript engine is free to execute other code, like handling user input, running animations, or executing other asynchronous tasks. Once the awaited promise settles, the async function is queued to resume where it left off.

This is just syntactic sugar over promise chains. await is a cleaner way of writing .then().

However, if you run a long, synchronous, CPU-intensive task inside an async function, that will block the main thread. async/await only helps with waiting for I/O (like network requests or file access), not with heavy computation.

Answer: "How does this relate to Promises?"

async/await is not an alternative to Promises; it is a different syntax for using them. An async function is just a function that is guaranteed to return a promise.

When asked to compare them, here are the key points:

  1. Syntax and Readability: async/await allows you to write asynchronous code that looks synchronous, avoiding nested callbacks or long .then() chains. This is its main advantage.
  2. Error Handling: try...catch in an async function can handle both synchronous errors and rejected promises from await expressions. In a promise chain, you need .catch() for asynchronous errors and a separate try...catch for synchronous errors that might occur inside a .then() block.
  3. Debugging: Debugging async/await code is more straightforward. You can step over await lines as if they were normal synchronous calls. Debugging promise chains can be more difficult, as you have to step through callbacks which can obscure the call stack.
  4. Conditionals: Conditional logic is much simpler with async/await. You can use standard if/else or for loops around your await calls, whereas with promises you often need to nest chains, which can get complicated.

Ultimately, async/await is a higher-level abstraction over Promises. Understanding both is essential.

Try it

Write an async function fetchWithRetry(url, maxRetries = 3) that fetches data from a URL. If the fetch call fails (either a network error or a non-2xx response), it should retry the request up to maxRetries times. Use a simple loop and try...catch. You can simulate a delay between retries if you want an extra challenge.

Next: We'll go from modern syntax back to the foundations with Prototypal Inheritance & new Keyword.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Error Handling & Debugging

Next

Prototypal Inheritance & `new` Keyword