From 6dc3c5e47bc9ea44362064063dac9de37019e23e Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Tue, 7 Jan 2020 22:40:52 +0100 Subject: [PATCH] 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 Reviewed-By: Rich Trott Reviewed-By: James M Snell --- doc/api/stream.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index 151da7da71311f..cdb2095aef1e85 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -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) + ]); })(); ```