Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda