Course contentsShow
← JavaScript
Lesson 2034 of 2,72342. Iteration Protocols Deep DiveFree lesson

Error Handling in For-Await-Of

Wrap for-await-of loops in try/catch to handle rejected promises or errors thrown during async iteration.

Error Handling in For-Await-Of

You'll learn how to safely handle errors when async iteration fails or promises reject.

When you use for-await-of to iterate over async iterables or arrays of promises, any rejected promise or thrown error will bubble up and potentially crash your code. Just like with regular async operations, you need to protect yourself with try/catch blocks.

Why Error Handling Matters Here

Think of for-await-of as walking through a series of doors that open one at a time. If any door is locked or broken, you'll stumble unless you're prepared. Each iteration awaits a promise, and any of those promises might reject. Without proper error handling, a single failure stops everything.

Wrapping For-Await-Of in Try/Catch

Place your entire for-await-of loop inside a try block, with a catch to handle any rejection:

async function processItems(asyncIterable) {
  try {
    for await (const item of asyncIterable) {
      console.log('Processing:', item);
      // Work with item
    }
  } catch (error) {
    console.error('Iteration failed:', error);
    // Handle the error gracefully
  }
}

If any promise rejects during iteration, the loop stops immediately and control jumps to your catch block.

With Promise Arrays

const promises = [
  Promise.resolve(1),
  Promise.reject('Oops!'),
  Promise.resolve(3)
];

async function run() {
  try {
    for await (const value of promises) {
      console.log(value); // Only logs: 1
    }
  } catch (error) {
    console.error('Caught:', error); // "Caught: Oops!"
  }
}

The loop stops at the first rejection, just like awaiting that promise directly would.

Key Takeaway: Always wrap for-await-of loops in try/catch blocks to handle rejected promises or errors thrown during async iteration—without them, a single failure will crash your async function.