Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda