Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda