How to use generator.next() inside while loop?

1.4k views Asked by At

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?

1

There are 1 answers

3
Bergi On BEST ANSWER

And I want to use generator.next() function inside it.

There's absolutely no reason to use a generator here. The plain code

{
    let value = 1;
    while (true) {
        getPage(value++);
    }
}

does exactly the same as calling the pendingPage generator and iterating it forever.

So, what is the problem with it?

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 that getPage and specfically service.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 bounded for loop, the iteration ended at some point and the callbacks had a chance to get called.

I want to retrieve info and put it to console.log. I want to do it async with generator, async/await and infinite while loop.

Omit the generator - it's not asynchronous anyway. You can do it only with async/await and an infinite loop:

(async function() {
    let value = 1;
    while (true) {
        await getPage(value++);
    }
}());

That's still an infinite loop, but it's suspended at every await to allow other things to happen.