diff --git a/lib/internal/streams/async_iterator.js b/lib/internal/streams/async_iterator.js index 8755e22de0d00f..ced9c77c4f50e2 100644 --- a/lib/internal/streams/async_iterator.js +++ b/lib/internal/streams/async_iterator.js @@ -78,20 +78,18 @@ 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) => { - 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)); - } - }); - } + process.nextTick(() => { + if (this[kError]) { + reject(this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); }); } diff --git a/test/parallel/test-stream-readable-async-iterators.js b/test/parallel/test-stream-readable-async-iterators.js index ded77e01da3d9b..c8b0e5151af0aa 100644 --- a/test/parallel/test-stream-readable-async-iterators.js +++ b/test/parallel/test-stream-readable-async-iterators.js @@ -484,23 +484,6 @@ 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); - })); - } } { @@ -544,5 +527,24 @@ async function tests() { p.then(common.mustCall()).catch(common.mustNotCall()); } +{ + // AsyncIterator should finish correctly if destroyed. + + const r = new Readable({ + objectMode: true, + read() { + } + }); + + r.destroy(); + r.on('close', () => { + const it = r[Symbol.asyncIterator](); + const next = it.next(); + next + .then(common.mustCall(({ done }) => assert.strictEqual(done, true))) + .catch(common.mustNotCall()); + }); +} + // To avoid missing some tests if a promise does not resolve tests().then(common.mustCall());