Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions lib/internal/streams/iter/consumers.js
Original file line number Diff line number Diff line change
Expand Up @@ -463,20 +463,11 @@ function merge(...args) {
if (result.done) {
activeCount--;
} else {
ArrayPrototypePush(ready, result.value);
// Immediately request the next value from this source
// (at most one pending .next() per source)
PromisePrototypeThen(
iterator.next(),
(r) => onSettled(iterator, r),
(err) => {
ArrayPrototypePush(ready, { __proto__: null, error: err });
if (waitResolve) {
waitResolve();
waitResolve = null;
}
},
);
ArrayPrototypePush(ready, {
__proto__: null,
iterator,
value: result.value,
});
}
if (waitResolve) {
waitResolve();
Expand Down Expand Up @@ -513,7 +504,18 @@ function merge(...args) {
if (item?.error) {
throw item.error;
}
yield item;
yield item.value;
PromisePrototypeThen(
item.iterator.next(),
(r) => onSettled(item.iterator, r),
(err) => {
ArrayPrototypePush(ready, { __proto__: null, error: err });
if (waitResolve) {
waitResolve();
waitResolve = null;
}
},
);
}

// If sources are still active, wait for the next settlement
Expand Down
27 changes: 27 additions & 0 deletions test/parallel/test-stream-iter-consumers-merge.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,32 @@ async function testMergeSignalDuringPendingMultiSourceRead() {
await assert.rejects(next, { name: 'AbortError' });
}

async function testMergeDoesNotDrainSourcesWhileIdle() {
function source(n) {
return {
__proto__: null,
pulls: 0,
async *[Symbol.asyncIterator]() {
while (this.pulls < n) {
yield [Buffer.from(`${++this.pulls}`)];
}
},
};
}

const a = source(5);
const b = source(5);
const iterator = merge(a, b)[Symbol.asyncIterator]();

await iterator.next();
await new Promise(setImmediate);

assert.strictEqual(a.pulls, 1);
assert.strictEqual(b.pulls, 1);

await iterator.return?.();
}

// merge() accepts string sources (normalized via from())
async function testMergeStringSources() {
const batches = [];
Expand Down Expand Up @@ -306,6 +332,7 @@ Promise.all([
testMergeConsumerBreak(),
testMergeSignalMidIteration(),
testMergeSignalDuringPendingMultiSourceRead(),
testMergeDoesNotDrainSourcesWhileIdle(),
testMergeStringSources(),
testMergeObjectLikeSources(),
testMergeCleanupErrorOnly(),
Expand Down
Loading