Skip to content

Commit 729b961

Browse files
ronagcodebytere
authored andcommitted
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: #31365 PR-URL: #31367 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 15b24b7 commit 729b961

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

doc/api/stream.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2644,12 +2644,22 @@ const finished = util.promisify(stream.finished);
26442644

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

2647+
function drain(writable) {
2648+
if (writable.destroyed) {
2649+
return Promise.reject(new Error('premature close'));
2650+
}
2651+
return Promise.race([
2652+
once(writable, 'drain'),
2653+
once(writable, 'close')
2654+
.then(() => Promise.reject(new Error('premature close')))
2655+
]);
2656+
}
2657+
26472658
async function pump(iterable, writable) {
26482659
for await (const chunk of iterable) {
26492660
// Handle backpressure on write().
26502661
if (!writable.write(chunk)) {
2651-
if (writable.destroyed) return;
2652-
await once(writable, 'drain');
2662+
await drain(writable);
26532663
}
26542664
}
26552665
writable.end();

0 commit comments

Comments
 (0)