Suppose I have a function that takes a generator and returns another generator of the first n
elements:
const take = function * (n, xs) {
console.assert(n >= 0);
let i = 0;
for (const x of xs) {
if (i == n) {
break;
}
yield x;
i++;
}
};
Usage like this:
const evens = function * () {
let i = 0;
while (true) {
yield i;
i += 2;
}
};
for (const x of take(10, evens())) {
console.log(x);
}
Now imagine that evens
is also async
(see this answer for setup):
const evensAsync = async function * () {
let i = 0;
while (true) {
yield i;
i += 2;
}
};
This, of course, does not work with take
:
const main = async () => {
for await (const x of take(10, evensAsync())) {
console.log(x);
}
};
main().catch(e => console.error(e));
Now, I can define a take
variant that is async
:
const takeAsync = async function * (n, xs) {
console.assert(n >= 0);
let i = 0;
for await (const x of xs) {
if (i == n) {
break;
}
yield x;
i++;
}
};
const main = async () => {
for await (const x of takeAsync(10, evensAsync())) {
console.log(x);
}
};
main().catch(e => console.error(e));
... but what a hassle!
Is there a way to automatically "asyncify" generator functions in JavaScript?