Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Asynchronous Issue with Javascript FileReader

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!