Skip to content

Commit 4edc1ab

Browse files
rluvatondanielleadams
authored andcommitted
stream: dont wait for next item in take when finished
PR-URL: #47132 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Erick Wendel <erick.workspace@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Debadree Chatterjee <debadree333@gmail.com>
1 parent e0a00eb commit 4edc1ab

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

lib/internal/streams/operators.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,10 @@ function take(number, options = undefined) {
409409
}
410410
if (number-- > 0) {
411411
yield val;
412-
} else {
412+
}
413+
414+
// Don't get another item from iterator in case we reached the end
415+
if (number <= 0) {
413416
return;
414417
}
415418
}

test/parallel/test-stream-drop-take.js

+23-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const common = require('../common');
44
const {
55
Readable,
66
} = require('stream');
7-
const { deepStrictEqual, rejects, throws } = require('assert');
7+
const { deepStrictEqual, rejects, throws, strictEqual } = require('assert');
88

99
const { from } = Readable;
1010

@@ -49,6 +49,28 @@ const naturals = () => from(async function*() {
4949
})().then(common.mustCall());
5050
}
5151

52+
53+
// Don't wait for next item in the original stream when already consumed the requested take amount
54+
{
55+
let reached = false;
56+
let resolve;
57+
const promise = new Promise((res) => resolve = res);
58+
59+
const stream = from((async function *() {
60+
yield 1;
61+
await promise;
62+
reached = true;
63+
yield 2;
64+
})());
65+
66+
stream.take(1)
67+
.toArray()
68+
.then(common.mustCall(() => {
69+
strictEqual(reached, false);
70+
}))
71+
.finally(() => resolve());
72+
}
73+
5274
{
5375
// Coercion
5476
(async () => {

0 commit comments

Comments
 (0)