JS forEach - 按加载顺序处理图像文件而不是随机

JS forEach - process images files in the order they are loaded not random

我想上传多张图片(不同尺寸),压缩每张图片并按照上传顺序将其添加到 PDF 文件中。当所有上传的图片处理完成后我想保存PDF文件

在附图中,FileList 的顺序是正确的,但是当我尝试处理它们时,顺序完全错误。它从文件[13](最小文件)开始,然后生成 pdf,然后处理其余图像。

如何正确执行此操作并确保仅在所有图像按正确顺序处理后才保存 PDF 非常感谢!

我有一个输入文件:

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

我有处理图像的功能:

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);
    });

});

Array#forEach更改为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
});

使用现代 async / await 语法,这看起来稍微好一点:

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

查看 以进一步了解循环中的承诺。