Skip to content

Commit

Permalink
docs: 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
  • Loading branch information
ronag committed Jan 7, 2020
1 parent 2551a21 commit a778098
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions doc/api/stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -2647,15 +2647,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.destroyed) return;
if (!writable.write(chunk))
await once(writable, 'drain');
if (writable.destroyed) return;
}
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 a778098

Please sign in to comment.