0

Hmm how can I make OnLoad async in this case?

Otherwise I have to throw in many code within the OnLoad closure.

$.each(data, function() {
  albumPhoto = 'http://assets.example.com/' + this.photo;

  var temp_img = new Image(),
    albumPhotoWidth, albumPhotoHeight

  temp_img.src = albumPhoto;
  temp_img.onload = function() {
    console.log(this.naturalWidth) // have something
    albumPhotoWidth = this.naturalWidth;
    albumPhotoHeight = this.naturalHeight;
  }

  console.log(albumPhotoWidth) //undefined ?? I want to use it here

});
RPichioli
  • 3,245
  • 2
  • 25
  • 29
Maria Jane
  • 2,353
  • 6
  • 23
  • 39
  • 1
    I'm not sure what you're asking as `onload()` *is* asynchronous. You can only guarantee that the `albumPhotoWidth` (and height) variables have been filled in the `onload` handler, so only use them there. – Rory McCrossan Sep 21 '16 at 16:33
  • @RoryMcCrossan I want to it to be outside possilbe? – Maria Jane Sep 21 '16 at 16:37
  • As you can see in your code, it isn't possible to access `albumPhotoWidth` in the `$.each` closure because `console.log(albumPhotoWidth)` will execute **before** `temp_img.onload` runs, which results in `albumPhotoWidth` being `undefined`. You have to access the image data in the `onload` function. But that doesn't stop you from using a promise or another function to use the image data. – Mr. Meeseeks Sep 21 '16 at 16:46
  • how to use promises within a callback? I thought I have to put my later login within onload function? – Maria Jane Sep 23 '16 at 16:56

0 Answers0