# async/await Patterns

> Explain async/await in JavaScript. What are the common patterns and pitfalls?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-async-await
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

Explain async/await in JavaScript. What are the common patterns and pitfalls?

## Answer

async/await is syntactic sugar over Promises that makes asynchronous code look synchronous. An async function always returns a Promise. The await keyword pauses execution until the promise settles, then returns its resolved value or throws the rejection.

Common patterns include sequential execution (await one after another), parallel execution (Promise.all with await), error handling (try/catch blocks), and retry logic. A major pitfall is accidentally running async operations sequentially when they could run in parallel.

Key rules: await can only be used inside async functions (or at the top level of ES modules). Error handling with try/catch replaces .then/.catch chains. If you forget to await a promise, you get the promise object instead of the value.

**What await really does. The body runs synchronously until await; the rest resumes as a microtask. Edit the program under Tweak.**

1. **An async function starts synchronously**: Code before the first await runs immediately when the function is called.
2. **await pauses the function**: The remainder is queued as a microtask and the caller continues.
3. **Microtasks run in queue order**: The resumed function and other promise callbacks run in the order they were queued.
4. **Output**: 1, inside, 2, inside resumed, then.

## Code examples

### Sequential vs Parallel Execution

```
function delay(ms, value) {
  return new Promise(res => setTimeout(() => res(value), ms));
}

async function sequential() {
  const start = Date.now();
  const a = await delay(100, 'A');
  const b = await delay(100, 'B');
  console.log(`Sequential: ${a}, ${b} in ${Date.now() - start}ms`);
}

async function parallel() {
  const start = Date.now();
  const [a, b] = await Promise.all([
    delay(100, 'A'),
    delay(100, 'B')
  ]);
  console.log(`Parallel: ${a}, ${b} in ${Date.now() - start}ms`);
}

sequential();
parallel();
```

Sequential awaits finish one after another (200ms total). Promise.all runs them in parallel (100ms total). Always use parallel when operations are independent.

### Error Handling Patterns

```
async function fetchData(shouldFail) {
  if (shouldFail) throw new Error('Network error');
  return { data: 'success' };
}

// Pattern 1: try/catch
async function withTryCatch() {
  try {
    const result = await fetchData(true);
    console.log(result);
  } catch (err) {
    console.log('Caught:', err.message);
  } finally {
    console.log('Cleanup done');
  }
}

// Pattern 2: .catch() on await
async function withCatch() {
  const result = await fetchData(true).catch(err => {
    console.log('Handled:', err.message);
    return { data: 'fallback' };
  });
  console.log(result);
}

// Pattern 3: Go-style error tuple
async function safeAsync(promise) {
  try {
    const data = await promise;
    return [null, data];
  } catch (err) {
    return [err, null];
  }
}

await withTryCatch();
await withCatch();
const [err, data] = await safeAsync(fetchData(false));
console.log('Go-style:', err, data);
```

Three error handling patterns: classic try/catch, .catch() for inline fallbacks, and Go-style error tuples for clean handling without try/catch blocks.

### Async Iteration and Retry Pattern

```
// Process items sequentially with for...of
async function processItems(items) {
  const results = [];
  for (const item of items) {
    const result = await processOne(item);
    results.push(result);
  }
  return results;
}

function processOne(item) {
  return new Promise(res =>
    setTimeout(() => res(item.toUpperCase()), 50)
  );
}

// Retry pattern
async function retry(fn, retries = 3, delay = 100) {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (err) {
      console.log(`Attempt ${i + 1} failed: ${err.message}`);
      if (i === retries - 1) throw err;
      await new Promise(r => setTimeout(r, delay));
    }
  }
}

const results = await processItems(['hello', 'world']);
console.log(results);

let attempt = 0;
await retry(async () => {
  attempt++;
  if (attempt < 3) throw new Error('not yet');
  return 'success';
}).then(r => console.log('Retry result:', r));
```

for...of with await processes items sequentially. The retry pattern is essential for network requests. Note: forEach does NOT await - use for...of instead.

## Key points

- async functions ALWAYS return a promise, even if you return a plain value
- await only pauses the async function, not the entire program
- forEach with async callbacks does not await - use for...of or Promise.all(arr.map())

## Common follow-up questions

- What is the difference between return and return await inside async functions?
- How does top-level await work in ES modules?
- How would you limit concurrency when processing many async operations?

## Interview tips

- Always show the sequential vs parallel comparison - it demonstrates practical awareness
- Mention the forEach pitfall - this is a common source of bugs
- Know when to use for...of (sequential) vs Promise.all(map()) (parallel)

## Concepts covered

async, await, Error Handling, Parallel Execution, Sequential Execution, Top-level await

Previous: [Promises Deep Dive](https://www.internhack.in/learn/interview/javascript-interview/js-promises-deep) · Next: [Type Coercion & Comparison](https://www.internhack.in/learn/interview/javascript-interview/js-type-coercion) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Modules (CommonJS vs ESM)](https://www.internhack.in/learn/interview/javascript-interview/js-modules)
- [DOM Manipulation & Events](https://www.internhack.in/learn/interview/javascript-interview/js-dom-manipulation)
- [Event Delegation & Bubbling](https://www.internhack.in/learn/interview/javascript-interview/js-event-delegation)
- [Web APIs (localStorage, fetch, etc.)](https://www.internhack.in/learn/interview/javascript-interview/js-web-apis)
- [Event Bubbling, Capturing & Event Flow](https://www.internhack.in/learn/interview/javascript-interview/js-event-bubbling)
- [Higher-Order Functions](https://www.internhack.in/learn/interview/javascript-interview/js-higher-order-functions)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
