Skip to content

Commit d51de78

Browse files
ronagMylesBorins
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 d0a96ab commit d51de78

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
@@ -2644,15 +2644,23 @@ const finished = util.promisify(stream.finished);
26442644

26452645
const writable = fs.createWriteStream('./file');
26462646

2647-
(async function() {
2647+
async function pump(iterator, writable) {
26482648
for await (const chunk of iterator) {
26492649
// Handle backpressure on write().
2650-
if (!writable.write(chunk))
2650+
if (!writable.write(chunk)) {
2651+
if (writable.destroyed) return;
26512652
await once(writable, 'drain');
2653+
}
26522654
}
26532655
writable.end();
2656+
}
2657+
2658+
(async function() {
26542659
// Ensure completion without errors.
2655-
await finished(writable);
2660+
await Promise.all([
2661+
pump(iterator, writable),
2662+
finished(writable)
2663+
]);
26562664
})();
26572665
```
26582666

0 commit comments

Comments
 (0)