Skip to content

Commit

Permalink
stream: fix async iterator destroyed error propagation
Browse files Browse the repository at this point in the history
There was an edge case where if _destroy calls the error callback
later than one tick the iterator would complete early and not
propgate the error.

PR-URL: #31314
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Minwoo Jung <nodecorelab@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
ronag authored and MylesBorins committed Jan 16, 2020
1 parent 4981f97 commit 499c41d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
24 changes: 13 additions & 11 deletions lib/internal/streams/async_iterator.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,20 @@ const ReadableStreamAsyncIteratorPrototype = ObjectSetPrototypeOf({
}

if (this[kStream].destroyed) {
// We need to defer via nextTick because if .destroy(err) is
// called, the error will be emitted via nextTick, and
// we cannot guarantee that there is no error lingering around
// waiting to be emitted.
return new Promise((resolve, reject) => {
process.nextTick(() => {
if (this[kError]) {
reject(this[kError]);
} else {
resolve(createIterResult(undefined, true));
}
});
if (this[kError]) {
reject(this[kError]);
} else if (this[kEnded]) {
resolve(createIterResult(undefined, true));
} else {
finished(this[kStream], (err) => {
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
reject(err);
} else {
resolve(createIterResult(undefined, true));
}
});
}
});
}

Expand Down
17 changes: 17 additions & 0 deletions test/parallel/test-stream-readable-async-iterators.js
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,23 @@ async function tests() {
assert.strictEqual(e, err);
})()]);
}

{
const _err = new Error('asd');
const r = new Readable({
read() {
},
destroy(err, callback) {
setTimeout(() => callback(_err), 1);
}
});

r.destroy();
const it = r[Symbol.asyncIterator]();
it.next().catch(common.mustCall((err) => {
assert.strictEqual(err, _err);
}));
}
}

{
Expand Down

0 comments on commit 499c41d

Please sign in to comment.