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: https://github.com/nodejs/node/issues/31222

PR-URL: https://github.com/nodejs/node/pull/31252
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Robert Nagy authored and Shelley Vohr committed 2020-03-16 19:40:43 -07:00
1 parent 623e1118a0
commit 4922184310
1 file changed
+11 -3
+11 -3
View File
@@ -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)
]);
})();
```