Skip to content

Commit 1b8eb22

Browse files
ronagTrott
authored andcommitted
doc: fix stream async iterator sample
The for await loop into writable loop could cause an unhandled exception in the case where we are waiting for data from the async iterable and this no `'error'` handler is registered on the writable. Fixes: #31222 PR-URL: #31252 Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Rich Trott <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent e468759 commit 1b8eb22

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

doc/api/stream.md

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2647,15 +2647,23 @@ const finished = util.promisify(stream.finished);
26472647

26482648
const writable = fs.createWriteStream('./file');
26492649

2650-
(async function() {
2650+
async function pump(iterator, writable) {
26512651
for await (const chunk of iterator) {
26522652
// Handle backpressure on write().
2653-
if (!writable.write(chunk))
2653+
if (!writable.write(chunk)) {
2654+
if (writable.destroyed) return;
26542655
await once(writable, 'drain');
2656+
}
26552657
}
26562658
writable.end();
2659+
}
2660+
2661+
(async function() {
26572662
// Ensure completion without errors.
2658-
await finished(writable);
2663+
await Promise.all([
2664+
pump(iterator, writable),
2665+
finished(writable)
2666+
]);
26592667
})();
26602668
```
26612669

0 commit comments

Comments
 (0)