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

560
Visualizações
JS forEach - process images files in the order they are loaded not random

I want to upload multiple images (different sizes), compress each image and add it to a PDF file in the order they are uploaded. When all the uploaded images are processed I want to save the PDF file

In the attached image the FileList is in the correct order but when I try to process them the order is completly wrong. It starts with the files[13] (the smallest file) then generate the pdf and then process the rest of the images.

How is the correct way to implement this and to make sure the PDF is saved only after all the images are proccesed in the correct order Many thanks!

I have an input file:

<input id="file" type="file" accept="image/*" multiple .....>

And I have a function to to process the images:

Array.from(files).forEach(async (file: any, i: number) => {
    console.log("Index inside forEach: "+i);
    imageCompression(file, compressOptions).then(function (compressedFile) {
            let fileUrl = URL.createObjectURL(compressedFile)
            let fileType = compressedFile.type === "image/png" ? "PNG" : "JPEG";
            const pdfWidth = PDF.internal.pageSize.getWidth();
            const pdfHeight = PDF.internal.pageSize.getHeight();
            PDF.addImage(fileUrl, fileType, 0, 0, pdfWidth, pdfHeight, "alias"+i, 'SLOW');
            
            console.log("Index inside imageCompression: "+ i + " -> " + compressedFile.name);
            if ( i < files.length - 1) { 
                PDF.addPage('a4');
            }
            if ( i === files.length - 1) { 
                console.log('!!!! GENERATE PDF');
                PDF.save('fisa_'+new Date().getTime()+'.pdf');
            }
    })
    .catch(function (error) {
            console.log(error.message);
    });

}); enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Change Array#forEach to Array#map:

const compressions = Array.from(files).map((file) => {
  return imageCompression(file, compressOptions);
});

Promise.all(compressions).then((compressedImages) => {
  // the ordering of images in `compressedImages` is the same as in `files`
  // you can do the PDF.addImage(...) and PDF.addPage(...) bits here
});

With the modern async / await syntax this looks slightly better:

const compressions = Array.from(files).map((file) => {
  return imageCompression(file, compressOptions);
});

const compressedImages = await Promise.all(compressions);

// the ordering of images in `compressedImages` is the same as in `files`
// you can do the PDF.addImage(...) and PDF.addPage(...) bits here

Check out this answer for additional insights into promises in loops.

about 4 years ago · Juan Pablo Isaza Relatório
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