How to use a loop Inside Playwright or async

BlackMickey

Newbie
Joined
Mar 14, 2021
Messages
38
Reaction score
16
So I am having some trouble trying to figure this out, does any of you guys know how to do it?


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

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

})();


How can I make a loop inside an async function? I just wanna read some stuff form a csv and use it later multiple times
 
I think what you want to know is, "How can I perform an async operation on each member of an array using Promise.all()?"

This is the code you're looking for:

Code:
const promises = data.map(async row => {
  const [name, address, url] = row;

  await page.goto(url);

  // Do other things
});

await Promise.all(promises);

Explanation: When you declare a function as async, it will return a promise. When you pass an async callback to data.map(), an array of promises is returned. You can then pass this array to Promise.all() for simultaneous processing.

Btw, your code has a bug where you are calling Promise.all() inside the loop. Also, you're passing data to page.goto(). data is probably an array of row values, not a URL. You should check the documentation.
 
Back
Top