0

I have tired to return value in callback function. How can I return value in this code?

let image = new Image();
image.onload = function createResolation() {
  var width = this.width;
  var height = this.height;
  return width, height;
};
image.src = URL.createObjectURL(image);

createResolation();
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Fxc Jahid
  • 23
  • 2

1 Answers1

0

What I like to do to return multiple values is just return an object.

So using your example, you would:

let image = new Image();
let myImage = {};

image.onload = function (dimensions) {
    var width = dimensions.width;
    var height = dimensions.height;
    
    //Option A (move your "constructor code" to another function)
    createResolution(width, height)
    
    //Option B
    myImage.width = width;
    myImage.height = height;
};

image.src = URL.createObjectURL(image);

function createResolution(width, height) {
    //Here you can store the dimensions 
    myImage.width = width; 
    myImage.height = height;
});

This more so looks like what you are trying to accomplish:

let image = new Image();

function createResolution (dimensions) {
    this.width = dimensions.width;
    this.height = dimensions.height;
};

image.onload = createResolution;
leroyjenkinss24
  • 472
  • 3
  • 8
  • getting error: `Uncaught ReferenceError: createResolation is not defined` – Fxc Jahid Sep 08 '20 at 19:39
  • The reason you getting undefined is because "image.onload" needs to be: image.onload = function () {... callback code here } – leroyjenkinss24 Sep 08 '20 at 19:42
  • @FxcJahid I have edited my answer for you. What you need to understand is that image.onload is the callback itself, meaning the Image class will call onload with the given function address we have set it to. – leroyjenkinss24 Sep 08 '20 at 20:00
  • Thanks, How can i uses this – Fxc Jahid Sep 08 '20 at 20:28
  • @FxcJahid What do you mean? Also, if I have answered you question would you please mark my answer as correct. – leroyjenkinss24 Sep 08 '20 at 20:32
  • `let image = new Image(); image.src = URL.createObjectURL(t); image.onload = getResolation; function getResolation() { let width = image.width; let height = image.height; return { 'width': width, 'height': height }; } var obj = new getResolation(); console.log(obj.width); console.log(obj.height); ` – Fxc Jahid Sep 09 '20 at 07:16
  • @FxcJahid do you have a reddit account or something we could use to exchange messages? – leroyjenkinss24 Sep 09 '20 at 12:07