I have generator
function* pendingPage() {
let value = 1;
while (true)
yield getPage(value++);
}
I have getPage()
function
async function getPage(value) {
const page = await service.getValidations(value);
(page.data.customers.length === 0) ? service.isCustomersFinished = false : console.log(page.data.customers);
}
I have while infinite loop with the following syntax:
let generator = pendingPage()
while(true){
generator.next();
}
And I want to use generator.next()
function inside it. But the generator does not work.
I tried with the for
loop, and it works fine.
So, what is the problem with it and how to use generator.next()
inside infinite while loop?
There's absolutely no reason to use a generator here. The plain code
does exactly the same as calling the
pendingPage
generator and iterating it forever.It's an infinite loop. That's the problem. It will call
getPage
forever, and block the whole process from doing anything else. That's kinda what you want if everything here was synchronous, but notice thatgetPage
and specficallyservice.getValidations
are asynchronous. Blocking everything includes preventing asynchronous callbacks from happening, which is the reason why you don't get any of the logs. With a boundedfor
loop, the iteration ended at some point and the callbacks had a chance to get called.Omit the generator - it's not asynchronous anyway. You can do it only with
async
/await
and an infinite loop:That's still an infinite loop, but it's suspended at every
await
to allow other things to happen.