Skip to content

Commit 4922184

Browse files
ronagcodebytere
authored andcommittedMar 17, 2020
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 623e111 commit 4922184

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed
 

‎doc/api/stream.md

+11-3
Original file line numberDiff line numberDiff line change
@@ -2639,15 +2639,23 @@ const finished = util.promisify(stream.finished);
26392639

26402640
const writable = fs.createWriteStream('./file');
26412641

2642-
(async function() {
2642+
async function pump(iterator, writable) {
26432643
for await (const chunk of iterator) {
26442644
// Handle backpressure on write().
2645-
if (!writable.write(chunk))
2645+
if (!writable.write(chunk)) {
2646+
if (writable.destroyed) return;
26462647
await once(writable, 'drain');
2648+
}
26472649
}
26482650
writable.end();
2651+
}
2652+
2653+
(async function() {
26492654
// Ensure completion without errors.
2650-
await finished(writable);
2655+
await Promise.all([
2656+
pump(iterator, writable),
2657+
finished(writable)
2658+
]);
26512659
})();
26522660
```
26532661

0 commit comments

Comments
 (0)