Cannot figure out how to return from $.getJSON

I am getting a page via json using a regex to grab a url, that’s all working.

What’s not working is how I get that URL back up through the layers of functions to stick that URL into an object.

Here is my codepen

here is what is happening
when you click “let’s Go” it triggers
it does a json call, then gets a name from that json
it passes that name like this

var listing =  {
    "planetName": json.name,
    "peopleName": json.residents[1],
    "planetImageURL": getPlanetImage(json.name)
  };

getPlanetImage is a function, but I am just getting undefined.
I know I am not returning it, but I can’t figure out where to put that return.

Or maybe I am doing something really stupid, either way I am totally at a loss???

Thanks
Joel

There’s a fundamental issue with how you’re going about writing the getPlanetImage function. The function is supposed to return the image address, except it can’t. jQuery will by default request external data in the form of an asynchronous request. This means that you need to prepare a callback to handle the data when it comes back, you can’t just return the data at the end of the function. This is because the response from the external request may not have come back by the time the function completes, therefor there’s nothing to return.

You’re approach should be more along these lines:

var listing =  {
    "planetName": json.name,
    "peopleName": json.residents[1]
};
var request = "https://allorigins.me/get?url=" + encodeURIComponent("http://starwars.wikia.com/wiki/" + json.name + "/Legends") + "&callback=?";
  $.getJSON(request, function(response) {
    listing.planetImageURL = response.contents.match(/<figure class="pi-item pi-image">(?:.|[\r\n])+?src="(.+?)\\*"(?:.|[\r\n])+?<\/figure>/)[1];
    $("#PlanetImage").attr('src', listing.planetImageURL);
});

Thanks, so I did know that I was going to have the async problem, I did originally structure my code the way you show. However I wanted to be able to get it all back together into one object and then make all the changes at once, so that the final product looked cleaner.

I think I need to do some more research on callbacks, I thought I was doing that with the nested functions, but I think I am very confused.

Thanks for the help.

1 Like

Yup, you might want to structure your code so that you can pass a callback into the getPlanetImage function as a parameter. And then, that callback can accept a parameter, which would be the request response. This way you can structure your code how you need to.

Also, you might want to look into JavaScript promises. They’re basically a more object oriented approach to handling asynchronous responses. I’m not sure if it will be directly useful in this case but it could be a good thing to keep in mind as they’re becoming more and more popular.