How do you add a timeout to an async iterator's next() call?
Short answer
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.
Advertisement
AModel answer
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.
Likely follow-ups
- How would you also clean up the timer if the original promise wins the race?
Related topics