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

Return and Throw Methods

Implement optional return() and throw() methods on async iterators for cleanup and error injection during iteration.

Return and Throw Methods

You'll learn how to implement optional return() and throw() methods on async iterators to handle cleanup and error injection gracefully.

Why These Methods Matter

Just like synchronous iterators, async iterators can define optional return() and throw() methods. The return() method lets you clean up resources when iteration stops early (like when a loop breaks). The throw() method allows external code to inject errors into the iterator, giving it a chance to handle them internally.

The return() Method

When a for await...of loop exits early (via break, return, or an exception), JavaScript calls the iterator's return() method if it exists:

const cleanupIterator = {
  [Symbol.asyncIterator]() {
    let count = 0;
    return {
      async next() {
        if (count < 10) {
          return { value: count++, done: false };
        }
        return { done: true };
      },
      async return() {
        console.log('Cleanup: releasing resources');
        return { done: true };
      }
    };
  }
};

for await (const num of cleanupIterator) {
  if (num === 3) break; // Triggers return()
}
// Logs: "Cleanup: releasing resources"

The throw() Method

The throw() method allows external code to inject an error into the iterator:

const iter = {
  async *[Symbol.asyncIterator]() {
    try {
      yield 1;
      yield 2;
    } catch (e) {
      console.log('Iterator caught:', e.message);
    }
  }
}[Symbol.asyncIterator]();

await iter.next(); // { value: 1, done: false }
await iter.throw(new Error('Injected!')); 
// Logs: "Iterator caught: Injected!"

Key Takeaway: Implementing optional return() and throw() methods on async iterators enables proper resource cleanup and error handling, making your iterators robust and predictable when iteration doesn't complete normally.