如何在forEach循环中使用JavaScript FileReader?

时间:2018-07-29 15:44:05

标签: javascript typescript angular6

 let base64Data: string;
 let attachment: Attachment;  
 let blob: Blob;
 docList.forEach(([pdfDoc, title]) => {
            blob = pdfDoc.output('blob'); 
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onloadend = function() {
              base64data = reader.result;
              attachment = new Attachment();
              attachment.setFilename(title);
              attachment.setContent(base64data);
              attachment.setType('application/pdf');
              attachments.push(attachment);
            }
         });

pdfDoc jsPDF 附件是我自己的带有指示字段的课程。

如果我在调试模式下运行以上代码并添加断点,则会按预期填充 attachments 数组。否则,数组将最终为空白。我知道同步循环和 FileReader 存在问题。我找到了以下答案

Looping through files for FileReader, output always contains last value from loop

但是我不确定如何将其应用于我的案件。有什么建议么?预先感谢。

1 个答案:

答案 0 :(得分:0)

我认为主要的问题是,您一方面杀死每个循环的数组attachment,另一方面却错过了复数s。

 let base64Data: string;
 let attachment: Attachment;  <<== plural s is missing
 let blob: Blob;

 docList.forEach(([pdfDoc, title]) => {
        blob = pdfDoc.output('blob'); 
        var reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onloadend = function() {
          base64data = reader.result;
          attachment = new Attachment(); <<== kills the array and overwrites it
          attachment.setFilename(title);
          attachment.setContent(base64data);
          attachment.setType('application/pdf');
          attachments.push(attachment); <<== never writes the value anywhere
        }
     });

所以请尝试这种方式:

 let attachments: Attachment; // with plural s

 docList.forEach(([pdfDoc, title]) => {
        const blob = pdfDoc.output('blob'); 
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onloadend = function() {
          const base64data = reader.result;
          const attachment = new Attachment(); // without plural s
          attachment.setFilename(title);
          attachment.setContent(base64data);
          attachment.setType('application/pdf');
          attachments.push(attachment); // writes to the intended array

          // how to know when the last item was added?
          if(attachments.length === docList.length) {
              showListContent();
          }
        }
     });

     function showListContent() {
         console.log(attachments);
     }

尽可能避免使用不必要的广泛范围的变量。如果适用,函数范围变量应始终是您的首选。