1

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 }
}

1 Answer 1

4

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;
};
Sign up to request clarification or add additional context in comments.

2 Comments

the result is a pending promise
call the function using await. await getFileDimensions()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.