Skip to content

Commit

Permalink
stream: fix fromAsyncGen
Browse files Browse the repository at this point in the history
Fixes: #40497

PR-URL: #40499
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Benjamin Gruenbaum <[email protected]>
  • Loading branch information
ronag authored and targos committed Oct 20, 2021
1 parent 7c42d9f commit 111f0bd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
14 changes: 10 additions & 4 deletions lib/internal/streams/duplexify.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,22 +209,28 @@ function fromAsyncGen(fn) {
const signal = ac.signal;
const value = fn(async function*() {
while (true) {
const { chunk, done, cb } = await promise;
const _promise = promise;
promise = null;
const { chunk, done, cb } = await _promise;
process.nextTick(cb);
if (done) return;
if (signal.aborted) throw new AbortError();
yield chunk;
({ promise, resolve } = createDeferredPromise());
yield chunk;
}
}(), { signal });

return {
value,
write(chunk, encoding, cb) {
resolve({ chunk, done: false, cb });
const _resolve = resolve;
resolve = null;
_resolve({ chunk, done: false, cb });
},
final(cb) {
resolve({ done: true, cb });
const _resolve = resolve;
resolve = null;
_resolve({ done: true, cb });
},
destroy(err, cb) {
ac.abort();
Expand Down
28 changes: 27 additions & 1 deletion test/parallel/test-stream-duplex-from.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const common = require('../common');
const assert = require('assert');
const { Duplex, Readable, Writable } = require('stream');
const { Duplex, Readable, Writable, pipeline } = require('stream');

{
const d = Duplex.from({
Expand Down Expand Up @@ -118,3 +118,29 @@ const { Duplex, Readable, Writable } = require('stream');
assert.strictEqual(d.readable, false);
}));
}

{
// https://github.com/nodejs/node/issues/40497
pipeline(
['abc\ndef\nghi'],
Duplex.from(async function * (source) {
let rest = '';
for await (const chunk of source) {
const lines = (rest + chunk.toString()).split('\n');
rest = lines.pop();
for (const line of lines) {
yield line;
}
}
yield rest;
}),
async function * (source) {
let ret = '';
for await (const x of source) {
ret += x;
}
assert.strictEqual(ret, 'abcdefghi');
},
common.mustCall(() => {}),
);
}

0 comments on commit 111f0bd

Please sign in to comment.