首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在forEach循环中使用JavaScript FileReader?

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

Stack Overflow用户
提问于 2018-07-29 23:44:05
回答 1查看 950关注 0票数 0
 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是一个jsPDFAttachment是我自己的类,具有指定的字段。

如果我在调试模式下运行上面的代码并添加断点,附件数组就会像我预期的那样被填充。否则,该数组最终将为空。我知道在同步循环和FileReader时存在问题。我找到了以下答案

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

但我不确定如何将其应用到我的案例中。有什么建议吗?提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-07-30 02:18:59

我认为主要的问题是,一方面你用每个循环杀死你的数组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);
     }

尽量避免使用不必要的过大范围的变量。如果适用,函数作用域的变量应该始终是您的首选。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51581954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档