From a778098c87907606b17d006bb81252f322d9267d Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Tue, 7 Jan 2020 22:40:52 +0100 Subject: [PATCH] docs: 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 --- doc/api/stream.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index 650a164775776f..656a92e546c600 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -2647,15 +2647,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.destroyed) return; if (!writable.write(chunk)) await once(writable, 'drain'); + if (writable.destroyed) return; } writable.end(); +} + +(async function() { // Ensure completion without errors. - await finished(writable); + await Promise.all([ + pump(iterator, writable), + finished(writable) + ]); })(); ```