From 729b96137e5761783856563c1af6482956ce01c9 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Wed, 15 Jan 2020 10:29:06 +0100 Subject: [PATCH] doc: further fix async iterator example Further fixes an issue with the async iterator example where an incorrect assumption was made in regards that drain or error is always invoked after !write(). Fixes: https://github.com/nodejs/node/issues/31365 PR-URL: https://github.com/nodejs/node/pull/31367 Reviewed-By: Matteo Collina Reviewed-By: Luigi Pinca --- doc/api/stream.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index 2ae9a3f889a9bb..92dfe1a42a39bb 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -2644,12 +2644,22 @@ const finished = util.promisify(stream.finished); const writable = fs.createWriteStream('./file'); +function drain(writable) { + if (writable.destroyed) { + return Promise.reject(new Error('premature close')); + } + return Promise.race([ + once(writable, 'drain'), + once(writable, 'close') + .then(() => Promise.reject(new Error('premature close'))) + ]); +} + async function pump(iterable, writable) { for await (const chunk of iterable) { // Handle backpressure on write(). if (!writable.write(chunk)) { - if (writable.destroyed) return; - await once(writable, 'drain'); + await drain(writable); } } writable.end();