• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

116
Views
Using map function with Async/Await

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}`);
            }
        
        }
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 })
});
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error