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;Attachment是我自己的类,具有指定的字段。
如果我在调试模式下运行上面的代码并添加断点,附件数组就会像我预期的那样被填充。否则,该数组最终将为空。我知道在同步循环和FileReader时存在问题。我找到了以下答案
Looping through files for FileReader, output always contains last value from loop
但我不确定如何将其应用到我的案例中。有什么建议吗?提前谢谢。
发布于 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);
}
尽量避免使用不必要的过大范围的变量。如果适用,函数作用域的变量应该始终是您的首选。
https://stackoverflow.com/questions/51581954
复制相似问题