An event that only emits when the stream finishes successfully #2038
-
|
I'm using Got in stream mode with retry enabled. I'm looking for an event that only fires when the stream finishes. However, if I understand the code correctly, both |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
theres no single event for "final completion", but you can handle it by recursivly listening to the retry event. when a stream completes without emitting heres the pattern: import got from 'got';
function attachListeners(stream) {
stream.on('end', () => {
// This fires for each attempt, including retries
console.log('Stream ended (might retry)');
});
stream.on('retry', (retryCount, error, createRetryStream) => {
console.log(`Retrying (attempt ${retryCount})`);
const newStream = createRetryStream();
// Recursivley attach listeners to the new stream
attachListeners(newStream);
});
stream.on('close', () => {
// If we get here and no retry was emited, were done
if (!stream.listenerCount('retry')) {
console.log('Stream truly finished');
}
});
}
const stream = got.stream('https://example.com', {
retry: { limit: 3 }
});
attachListeners(stream);the key is that each retry creates a new stream, so you need to attach listeners to each one. the last stream in the chain (the one that completes without if |
Beta Was this translation helpful? Give feedback.
theres no single event for "final completion", but you can handle it by recursivly listening to the retry event. when a stream completes without emitting
retry, thats your final completion.heres the pattern: