What does return() do on an async iterator?
Short answer
return() is called automatically when a for-await-of loop exits early (via break, return, or an exception), giving the iterator a chance to run cleanup code such as closing a file handle or network connection.
Advertisement
AModel answer
return() is called automatically when a for-await-of loop exits early (via break, return, or an exception), giving the iterator a chance to run cleanup code such as closing a file handle or network connection.
async function* gen() {
try {
yield 1; yield 2; yield 3;
} finally {
console.log('cleanup ran');
}
}
for await (const v of gen()) { if (v === 2) break; }
// logs 'cleanup ran'Real-world example
Ensuring a database cursor or file stream is closed even if the consumer stops iterating early.
Likely follow-ups
- Does the same cleanup behavior apply to synchronous generators?
Related topics