Skip to content

Commit

Permalink
doc: further fix async iterator example
Browse files Browse the repository at this point in the history
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: nodejs#31365

PR-URL: nodejs#31367
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
ronag committed Jan 24, 2020
1 parent 8d14a8c commit 4fefd18
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions doc/api/stream.md
Expand Up @@ -2682,12 +2682,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();
Expand Down

0 comments on commit 4fefd18

Please sign in to comment.