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 <matteo.collina@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent d0a96ab commit d51de78

1 file changed

Lines changed: 11 additions & 3 deletions

File tree

‎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
constwritable=fs.createWriteStream('./file');
26462646

2647-
(asyncfunction() {
2647+
asyncfunctionpump(iterator, writable) {
26482648
forawait (constchunkofiterator) {
26492649
// Handle backpressure on write().
2650-
if (!writable.write(chunk))
2650+
if (!writable.write(chunk)) {
2651+
if (writable.destroyed) return;
26512652
awaitonce(writable, 'drain');
2653+
}
26522654
}
26532655
writable.end();
2656+
}
2657+
2658+
(asyncfunction() {
26542659
// Ensure completion without errors.
2655-
awaitfinished(writable);
2660+
awaitPromise.all([
2661+
pump(iterator, writable),
2662+
finished(writable)
2663+
]);
26562664
})();
26572665
```
26582666

0 commit comments

Comments
 (0)