Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
How to async properly in a foor loop

I am trying to store some data into a group of PDF files using Puppeteer. But when I try to run this code my app is freezing and I assume I am doing something wrong with the async and await code. It seems to be working properly, the documents are created properly in the folder of the project, but at some point node crashes and I must reboot my PC.

 const path = require("path");
 const puppeteer = require("puppeteer");
 const fs = require('fs');

 for (let index = 0; index < documentsToPDF.length; index ++) {
        const result = await generatePDF(documentsToPDF[index]);
        await createAndSavePDFInFile(documentsToPDF[index], result);
      }

async function generatePDF(browser, numdoc) {
  const filePage = await browser.newPage();
  filePage.setDefaultNavigationTimeout(0);
  await filePage.goto(renderPath(numdoc), {
    waitUntil: "networkidle0",
  });
  return filePage.pdf({
    format: "A4",
  });
}

async function createAndSavePDFInFile(numdoc, result) {
  console.log(result);
  if(result) {
    return fs.writeFile(
      path.join(__dirname, `../results/result-${numdoc}.pdf`),
      result,
      (error, result) => {
        if(error) console.log('error', err);
        else console.log(`PDF result-${numdoc}.pdf `);
      }
    ); 
  } else {
    console.log(`numdoc `, numdoc, ' could not be saved into pdf');
  }

}

Thanks for your help, I'm new to node and I'm learning :)

EDIT:

This loop now is working fine

for (let index = 0; index < documentsToPDF.length; index += 1) {
    const browser = await puppeteer.launch(puppeteerParams);
    const result = await generatePDF(browser,documentsToPDF[index]);
    await createAndSavePDFInFile(documentsToPDF[index], result);
    browser.close();
    console.log('Exp: ', documentsToPDF[index], ' SUCCESS');
}

But can I do something like this?

   const pdfPromises = [];
  for (let index = 0; index < documentsToPDF.length; index += 1) {
    pdfPromises.push(createPdf(puppeteer, puppeteerParams, documentsToPDF[index]))
  }

await Promise.all(pdfPromises);


async function createPdf(puppeteer, puppeteerParams, numexp) {
  const browser = await puppeteer.launch(puppeteerParams);
  const result = await generatePDF(browser, numexp);
  await createAndSavePDFInFile(numexp, result);
  browser.close();
  console.log('Exp: ', numexp, ' SUCCESS');
}

I've tried and it returns this error:

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 event listeners added. Use emitter.setMaxListeners() to increase limit.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!