Im learning how to use Puppeteer and the case is that when i try to map my data array object i can´t do it using the map function. is there a way map it with async/await or is there another way?
const puppeteer = require("puppeteer");
module.exports.screenshot = async (req, res) => {
let data = [
{ url: "someurl1", src: "someplace1" },
{ url: "someurl2", src: "someplace1" }
];
let browser = await puppeteer.launch();
let page = await browser.newPage();
try {
let files = data.map(info => (
await page.goto(info.url) //here i can´t await
await page.screenshot({ path: info.src }) //these two functions
));
await browser.close();
res.send({
data: files
})
} catch (error) {
console.error(`An error has occurred ${error}`);
}
}
You have a callback function inside map()
that is a separate block to the outer function.
To await inside you at minimum need to make that callback async as well
const files = data.map(async (info) => (
await page.goto(info.url),
await page.screenshot({ path: info.src })
));
If files is supposed to have the screenshot (the result of last await inside map()
), I think you need to add a comma between awaits. I added it above.
A more explicit syntax might be
const files = data.map(async (info) => {
await page.goto(info.url);
return await page.screenshot({ path: info.src })
});