简体   繁体   中英

How can I make a loop inside an async function with Playwright?

So I am trying to do really simple stuff with Playwright, I just need to go to the sites from an array I made with a csv

var csvsync = require('csvsync');
var fs = require('fs');
 
var csv = fs.readFileSync('sites.csv');
var data = csvsync.parse(csv);

const { chromium } = require('playwright');

(async () => {

const promises = [];


  const browser = await chromium.launch({
    headless: false
  });
  const context = await browser.newContext();

  // Open new page
  const page = await context.newPage();

  for(let i = 0; i <= data.length; i++) {
      // Go to https://www.google.com.br/?gws_rd=ssl
      await page.goto(`${data[i]}`);

      await Promise.all(promises);
  }
  await Promise.all(promises);
  // ---------------------
  await context.close();
  await browser.close();
})();

So, what is wrong with it?

A more thorough answer to aysnc for loops is here: Asynchronous Process inside a javascript for loop

But in short:

//Helper function
async function asyncForEach (array, callback) {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
    }
};

//usage
await asyncForEach( data, async d => {
    await page.goto(d);
});

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