Skip to content

Commit 6e383e2

Browse files
author
Zibi Braniecki
committed
Ensure that if the CachedAsyncIterable is called multiple times in parallel, it does return the correct value
1 parent 55dc676 commit 6e383e2

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/cached_async_iterable.mjs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,9 @@ export default class CachedAsyncIterable extends CachedIterable {
6060
return {
6161
async next() {
6262
if (cached.length <= cur) {
63-
cached.push(await cached.iterator.next());
63+
cached.push(cached.iterator.next());
6464
}
65-
return cached[cur++];
65+
return await cached[cur++];
6666
}
6767
};
6868
}

test/cached_async_iterable_test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,26 @@ suite("CachedAsyncIterable", function() {
170170
const first = await toArray(iterable);
171171
assert.deepEqual(await toArray(iterable), first);
172172
});
173+
174+
test("lazy iterable can be called multiple times in parallel", async function() {
175+
let counter = 0;
176+
177+
async function *generate() {
178+
while (true) {
179+
counter++;
180+
yield await Promise.resolve();
181+
}
182+
}
183+
184+
// We're testing that if the first call to asyncIterator has been
185+
// made, but the value of it has not been returned yet,
186+
// the consequitive call returns the same Promise rather than,
187+
// attempting to fetch the next item from the iterator.
188+
const iterable = new CachedAsyncIterable(generate());
189+
iterable[Symbol.asyncIterator]().next();
190+
await iterable[Symbol.asyncIterator]().next();
191+
assert.equal(counter, 1);
192+
});
173193
});
174194

175195
suite("async touchNext", function(){

0 commit comments

Comments
 (0)