-2

I'd like to set the width of an external image (from another url) into a variable, so I can use the newly assigned variable on another function.

The problem is that I get undefined message on the variable, see the code below.

var site_url = 'http://fabricjs.com/assets/1.svg';

function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}
var a = getMeta(site_url, function(width, height) { 
    return width; 
});

alert(a); //undefined

What am I doing wrong, how should I proceed ?

Horai Nuri
  • 5,358
  • 16
  • 75
  • 127

1 Answers1

1

When working with asynchronous functions, you need to put the rest of the code in the callback function (or use promises). Here, you need to put alert inside callback.

var a = getMeta(site_url, function(width, height) { 
  alert(width);
});
user7771338
  • 185
  • 6
  • I don't want to alert it, I want to use the variable 'a' which should be an integer with the width number. – Horai Nuri Mar 29 '17 at 00:34
  • Ok, but I've already said that you **must put the rest of the code** where you use `a` in the callback function. – user7771338 Mar 29 '17 at 00:35
  • when I print 'a' it's still undefined, is there a way so this variable is just a number ? why can't I return width; ? Can you show me an example ? – Horai Nuri Mar 29 '17 at 00:37
  • Nevermind, the duplicate says it's impossible – Horai Nuri Mar 29 '17 at 00:39
  • @Lindow. No, you didn't understand it. It is not impossible. You must write `a = width` at the start of the callback function and everything after it you must put inside callback. **You cannot return anything from asynchronous function** becauae it is called **after** you print `a`, understood? – user7771338 Mar 29 '17 at 00:40
  • I'm really visual and take time to understand when it's written, sorry to bother... But I think I get what you mean, I can only call width, height inside the getMeta function but I cannot assign it the integers to "a" as it was a number. – Horai Nuri Mar 29 '17 at 00:45
  • @Lindow. Correct. – user7771338 Mar 29 '17 at 00:46