Skip to content

Commit

Permalink
doc: fix stream async iterator sample
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
ronag authored and codebytere committed Mar 17, 2020
1 parent 623e111 commit 4922184
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions doc/api/stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -2639,15 +2639,23 @@ const finished = util.promisify(stream.finished);

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

(async function() {
async function pump(iterator, writable) {
for await (const chunk of iterator) {
// Handle backpressure on write().
if (!writable.write(chunk))
if (!writable.write(chunk)) {
if (writable.destroyed) return;
await once(writable, 'drain');
}
}
writable.end();
}

(async function() {
// Ensure completion without errors.
await finished(writable);
await Promise.all([
pump(iterator, writable),
finished(writable)
]);
})();
```

Expand Down

0 comments on commit 4922184

Please sign in to comment.