0

In my webapplication, I am trying to process an array of File Objects, which are attachments for the Email which will be sent. I go through this array in a function to get the File contents and add them to the attachments array of the message object. Following is the code:

export class Message {

  constructor(
    public subject: string = '',
    public text: string = '',

    public attachments: Attachment[] = []) {}
}

function getMessage(message: NewMessage, attachments: File[]) {
  attachments.forEach(file => {
    let newAttachment = new Attachment();
    newAttachment.dateiname = file.name;
    newAttachment.dateityp = file.type;
    newAttachment.size = file.size;

    const reader = new FileReader();
    reader.onload = (event) => {
      newAttachment.fileData = event.target.result.toString();
      message.attachments.push(newAttachment);

    };

    reader.readAsText(file);
  });
  return message;
}

The issue I am facing is due to the fact that the an instance of FileReader works asynchronously. My method returns before onload event fires and the file contents are added to the message object. I have tried returning the message object via onloadend event, but here I get the error that the function must return a value of type Message:

 reader.onloadend = () => {
  return message;
};

How can I solve this issue?

user1107888
  • 1,481
  • 5
  • 34
  • 55

0 Answers0