Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda