Home > other >  For loop run puppeteer function out of order
For loop run puppeteer function out of order

Time:03-29

I have a loop which contains an puppeteer function. The problem is that the loop is doing all puppeteer at the same time.

I've tried this:

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

Could you tell me what I'm doing wrong and how can fix this?

CodePudding user response:

Its is an async function, you have to keep a look out at the created browser.

something like this should help you.

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

Have a look at the library I build, it will solve your issue https://www.npmjs.com/package/puppeteer-express

  • Related