JavaScript › Async Iterators & Streams
How do you add a timeout to an async iterator's next() call?
AdvancedAnswer
Race the iterator's next() Promise against a Promise that rejects after a timeout using Promise.race(), so a slow or stalled source doesn't hang your consumer forever.
function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('timeout')), ms));
return Promise.race([promise, timeout]);
}
const { value } = await withTimeout(iterator.next(), 5000);Real-world example Cutting off a stalled WebSocket or SSE connection after a set idle period.