简体   繁体   English

puppeteer 不等待上一个循环迭代完成

[英]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.我试图建立一个循环,在每次迭代中,木偶操作员在搜索栏中输入一些内容,按 Enter,稍等片刻,然后对结果进行截图。

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.我缩短了我的代码,以便在输入搜索并按下 Enter 后截取屏幕截图,看起来它一次从数组的每个元素中键入 1 个字符。

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:这是生成的屏幕截图: 人偶截图

With this Promise.all() way, you do launch a concurrent execution (both .map() callbacks start synchronously, continue asynchronously and both their ends are awaited).使用这种Promise.all()方式,您确实启动了并发执行(两个.map()回调同步启动,异步继续并等待它们的两端)。 Try a for-of loop instead:尝试使用 for-of 循​​环:

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 });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM