For loop 运行 puppeteer 函数出错

For loop run puppeteer function out of order

我有一个包含木偶操作函数的循环。 问题是循环同时执行所有木偶操作。

我试过这个:

import puppeteer from "puppeteer"

(async function(){
    for(let i = 0; i < 3; i++){
        await launchPup().then(() => {
        });
    }
})()

async function launchPup() {
    puppeteer.launch({headless: false}).then(async browser => {
        await browser.newPage()
        await browser.close()
    })
}

你能告诉我我做错了什么吗?如何解决这个问题?

是异步函数,创建的浏览器一定要注意。

类似的内容应该对您有所帮助。

var totalOpenedbrowser = 0;
var minBrowser = 2;
const wait = () => new Promise((resolve) => setTimeout(resolve, 200))

(async function() {
  for (let i = 0; i < 3; i++) {

    await launchPup().then(() => {});
  }
})()



async function launchPup() {
  while (totalOpenedbrowser > = minBrowser)
    await wait(); // wait until there is a free slott
  totalOpenedbrowser++;
  puppeteer.launch({
    headless: false
  }).then(async browser => {
    await browser.newPage()
    await browser.close()
    totalOpenedbrowser--;
  })
}

看看我构建的库,它会解决你的问题 https://www.npmjs.com/package/puppeteer-express