-1

I have a piece of JS code in for loop:

window.gamesParse = {
    days: days,
    dates: dates,
    times: times,
    series: series,
    homes: homes,
    aways: aways,
    channels: channels
}

var image = $.get("assets/images/" + gamesParse.aways[i] + ".png");
if (image.status !== 404) {
    console.dir(image);
} else {
    console.dir(image);
}

Now, it returns the right Objects which have status property. But if I change image to image.status (or any other property or method), it returns undefined.
Is it normal? How can I access status property from there?

Mehdi Hoseini
  • 407
  • 1
  • 4
  • 12
  • Its okay! then what is the question? Do you want any answer for it? it is undefined because status property is not available in it. – Jai May 29 '15 at 11:20
  • @Jai I thought the undefined situation was not expected. question edited. – Mehdi Hoseini May 29 '15 at 11:23
  • Newbie error. Javascript is _asynchronous_. You have to wait for the `get` function to finish and come back with the result, before testing `image.status`. Use a callback function. `$.get("png", function(image){ console.log(image); })` – Jeremy Thille May 29 '15 at 11:35

2 Answers2

1

This is normal because $.get is asynchronous, which in this current code means that it loads data. But on the very next line you ask about the status of the image, which in fact is still loading. What you have to do is wait for the image to load, and then check the code. Something like:

$.get("assets/images/" + gamesParse.aways[i] + ".png", function(image) {
    // here image can have status
});
Andrey Popov
  • 7,362
  • 4
  • 38
  • 58
0

image is undefined because it's out of the get action, try to put it into a callback function. Like this:

$.get("assets/images/" + gamesParse.aways[i] + ".png", function(response) {
   if (response.status !== 404) {
        // do stuff here
    } else {
        // or here
    } 
});

Check the docs.

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60