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 <[email protected]>
Reviewed-By: Rich Trott <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
ronag authored and MylesBorins committed Jan 16, 2020
1 parent d0a96ab commit d51de78
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 @@ -2644,15 +2644,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 d51de78

Please sign in to comment.