Error Handling in Async Iterators
You'll learn how to catch and handle errors that occur when iterating over asynchronous data sources.
The Core Challenge
Async iterators can fail in two ways: the promise returned by next() might reject, or the value-producing logic might throw an error. Unlike sync iterators where you can wrap a for...of loop in try-catch, async iterators require careful handling of both promise rejections and thrown exceptions.
Catching Errors in for-await-of
When using for await...of, wrap the entire loop in a try-catch block to handle any errors from the async iterator:
async function consumeWithErrorHandling() {
const asyncIterable = {
[Symbol.asyncIterator]() {
let count = 0;
return {
async next() {
if (count === 2) {
throw new Error('Something went wrong!');
}
if (count >= 5) {
return { done: true };
}
count++;
return { value: count, done: false };
}
};
}
};
try {
for await (const value of asyncIterable) {
console.log(value); // 1, 2, then error
}
} catch (error) {
console.error('Caught error:', error.message);
}
}
Handling Errors Inside the Iterator
Build error handling directly into your async iterator's next() method:
const robustIterator = {
[Symbol.asyncIterator]() {
return {
async next() {
try {
// Risky async operation
const data = await fetchData();
return { value: data, done: false };
} catch (error) {
// Return error as value or rethrow
return { value: null, done: true };
}
}
};
}
};
You can either rethrow errors to let consumers handle them, return sentinel values, or return errors as regular values depending on your use case.
Key Takeaway: Always wrap for await...of loops in try-catch blocks and decide whether your async iterator should handle errors internally or propagate them to consumers.