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

258
Visualizações
javascript return values from .onload method from image object

I am calling the getFileDimensions in another file. I need this method to return values that are inside .onload() method. The values are right I need just to return them using the outer function.

export const getFileDimensions = file => {
    var reader = new FileReader();

    //Read the contents of Image File.
    reader.readAsDataURL(file);
    var width, height = null
    reader.onload = function (e) {

        //Initiate the JavaScript Image object.
        var image = new Image();

        //Set the Base64 string return from FileReader as source.
        image.src = e.target.result;

        //Validate the File Height and Width.
        image.onload = function () {
            console.log("Image loaded", this.width, this.height)
            height = this.height;
            width = this.width;
            return { width: this.width, height: this.height }
        };
        return { width: width, height: height }
    };
   return { width: width, height: height }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try using Promises

export const getFileDimensions = async (file) => {
  var reader = new FileReader();

  //Read the contents of Image File.
  reader.readAsDataURL(file);
  var width,
    height = null;
  const result = await new Promise((resolve) => {
    reader.onload = function (e) {
      //Initiate the JavaScript Image object.
      var image = new Image();

      //Set the Base64 string return from FileReader as source.
      image.src = e.target.result;

      //Validate the File Height and Width.
      image.onload = function () {
        console.log("Image loaded", this.width, this.height);
        height = this.height;
        width = this.width;
        resolve({ width: this.width, height: this.height });
      };
    };
  });
  return result;
};
about 4 years ago · Juan Pablo Isaza Relatório
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