简体   繁体   中英

NodeJS Wait for function in for loop to finish before continuing

I basically have this for loop which runs a function that opens a puppeteer window and goes to a link, however, I want this to be done sequentially as right now all the puppeteer windows open at the same time.

Here is the loop:

for(var i=0; i < 3; i++){
  if (i != 0){
    enter();
  }
}

And here is my function enter :

async function enter(){

   browser = await puppeteer.launch({headless: false});
   page = await browser.newPage();
   await page.goto(url);

}

Right now if I were to run that code 2 puppeteer windows would open however I would like 1 to open, go to the link, and then have the next one open and go to the link, and so on...

Any help is appreciated

You are not awaiting your enter call and that is reason it is not waiting. You need to await it.

for(var i=0; i < 3; i++){
  if (i != 0){
    await enter();
  }
}

You need to wrap your loop into an async function and await every enter() call:

async function openWindows() {
  for(var i=0; i < 3; i++){
    if (i != 0){
      await enter();
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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