Mr.Smithyyy
Mr.Smithyyy

Reputation: 1329

puppeteer doesn't wait for previous loop iteration to finish

I'm trying to set up a loop where in each iteration puppeteer types something into the search bar, presses enter, waits a little bit, and then screenshots the results.

However, what ends up happening is it seems that each iteration of the loop is running in parallel.

I shortened my code so that it takes the screenshot after the search has been typed and enter has been pressed and it looks like it types 1 character from each element of the array at a time.

const lookups = ['INPUT1', 'INPUT2'];

const promises = lookups.map(async lookup => {
    await page.type('.text', lookup);
    await page.keyboard.press(String.fromCharCode(13));
    await page.waitFor(5000);

    await page.screenshot({ path: `test.png`, type: 'png', fullPage: true });
});

await Promise.all(promises);

Here is the resulting screenshot generated: puppeteer screenshot

Upvotes: 1

Views: 194

Answers (1)

vsemozhebuty
vsemozhebuty

Reputation: 13772

With this Promise.all() way, you do launch a concurrent execution (both .map() callbacks start synchronously, continue asynchronously and both their ends are awaited). Try a for-of loop instead:

const lookups = ['INPUT1', 'INPUT2'];

for (const lookup of lookups) {
    await page.type('.text', lookup);
    await page.keyboard.press(String.fromCharCode(13));
    await page.waitFor(5000);

    await page.screenshot({ path: `test.png`, type: 'png', fullPage: true });
}

Upvotes: 3

Related Questions