skip to Main Content

I want to implement a for loop that calls a async function and actually await for it to end, but I don’t have an array, I have a number of runs, so I can only think of doing this

for (let i = 1; i === numberOfPages; i += 1) {
            await getPageDetails();
            await this.page.evaluate(async () => {
                const nextButton = document.querySelector('[aria-label="Next Page"]') as HTMLElement;
                nextButton?.click();
            });
        }

Any ideas?

The for loop should await the async function

2

Answers


  1. Your loop never runs since it never passes the continue condition (except with 1 page as noted in the comment), fix the for loop to:

    for(let i = 0; i < numberOfPages; i++) {
    

    Since you don’t use i inside the loop, a simpler version could be:

    let count = numberOfPages;
    while(count--) {
       ...
    }
    

    If you don’t need numberOfPages after the loop anymore you can mutate it:

    while(numberOfPages--) {
       ...
    }
    
    Login or Signup to reply.
  2. You’re almost there, this should work:

    for (let i = 1; i <= numberOfPages; i += 1) {
      await getPageDetails();
      const nextButton = document.querySelector('[aria-label="Next Page"]');
      nextButton?.click();
    }
    
    

    Edit:
    However, if you have event listeners attached to the button’s on-click event – those will not be awaited. In that case you should probably call them direct instead of clicking the button, but you’d have to show us that code as well.

    And if the next-page button actually is a link and clicking it triggers a full page-reload (i.e. if you have a multi-page app and not a single-page-app), then all your JavaScript will be terminated and started again, so then you’re pretty much out of luck.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search