Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix drain() function for "Piping to writable streams from async iterators" #34018

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions doc/api/stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -2890,20 +2890,32 @@ In the scenario of writing to a writable stream from an async iterator, ensure
the correct handling of backpressure and errors.

```js
const { once } = require('events');
const finished = util.promisify(stream.finished);

const writable = fs.createWriteStream('./file');

function drain(writable) {
const resolve = () => Promise.resolve();
const rejectError = (err) => Promise.reject(err);
const rejectPrematureClose = () => Promise.reject(new Error('premature close of writable stream'));

if (writable.destroyed) {
return Promise.reject(new Error('premature close'));
return rejectPrematureClose();
}

try {
// register event listeners and wait for whatever event gets emitted first
await Promise.race([
writable.once('drain', resolve),
writable.once('error', rejectError),
writable.once('close', rejectPrematureClose),
]);
} finally {
// ensure that all the registered event listeners get removed again
writable.removeListener('drain', resolve);
writable.removeListener('error', rejectError);
writable.removeListener('close', rejectPrematureClose);
}
return Promise.race([
once(writable, 'drain'),
once(writable, 'close')
.then(() => Promise.reject(new Error('premature close')))
]);
}

async function pump(iterable, writable) {
Expand Down