2

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?

  • We could ask the same from you "what is wrong with it?" Can you add this detail to your post, please? At the moment I can only guess what can be the problem, you might get an `UnhandledPromiseRejectionWarning: page.goto: Protocol error (Page.navigate): Cannot navigate to invalid URL` error on the last URL, that can be solved. Iterating in async functions is tricky as rbucinell already suggested, but your current code handles it correctly (even if the `promises` array is not yet populated in your example) – theDavidBarton Apr 05 '21 at 12:18

1 Answers1

0

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);
});
rbucinell
  • 73
  • 1
  • 2
  • 10