You can't return a value in your synchronous function that was acquired from an asynchronous operation. The async operation won't complete until sometime later so it simply isn't available yet when your getGithubURL()
function returns. It's a matter of timing and just something that javascript can't do.
You can solve your problem by restructuring how you use promises. What you want to do is to make a .then()
handler be the consumer of the final data. That way you can pass the data back through your promise structure. You also want to make use of the promise that $.getJSON()
already returns - no need to create your own promise here.
Here's one way to do that.
getGithubURL("bullcitydave").then(function(url) {
// you can use the avatar url here
});
function getGithubURL(name){
var ghUserURL = 'https://api.github.com/users/bullcitydave?client_id=-----&client_secret=------';
return $.getJSON(ghUserURL).then(function(data) {
return data.avatar_url;
});
};
You call $.getJSON()
. It returns a promise which you add a .then()
handler on in order to extract the actual data you want. From the .then()
handler, you return the final data you want. The $.getJSON().then()
sequence creates a new promise which is what you return from your getGithubURL()
function and is not resolved until the getJSON().then()
sequence is done. That will present your avatar URL to the outer .then()
handler as shown in the code
above.
Or, if the caller of your getGithubURL()
function isn't going to use promises, then you can make your function take a callback like this:
getGithubURL("bullcitydave", function(url) {
// you can use the avatar url here
});
function getGithubURL(name, fn) {
var ghUserURL = 'https://api.github.com/users/bullcitydave?client_id=-----&client_secret=------';
$.getJSON(ghUserURL).then(function(data) {
// call the callback and pass it the avatar url
fn(data.avatar_url);
});
};