Minh Le
Minh Le

Reputation: 47

Using callback function to change the value of a variable defined outsite of getJSON

Ok, so I have this function.

function check(username){
    var result = "default";  
    $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){
      if(data.stream == null)
        result = 'offline';
      else 
        result = 'online';

    }).fail(function(){
        result = 'notfound';
       });

   return result;
}

console.log(check('freecodecamp'));

The problem is that what I received in console log is "default", not "offline", nor "online, nor "notfound" as I expect.

I tried to move the console.log() line before the check() function but it doesn't work. I also tried to define the var result globally but it doesn't work either.

Any help would be appreciated !

Upvotes: 0

Views: 61

Answers (1)

Andreas Grech
Andreas Grech

Reputation: 107950

This is how your code should be written:

function check(username, callback){
    var result = "default";  
    $.getJSON('https://api.twitch.tv/kraken/streams/' + username, function(data){
      if(data.stream == null) {
        result = 'offline';
      } else {
        result = 'online';
      }

      callback(result);
    }).fail(function(){
        result = 'notfound';
        callback(result);
    });
}

check('freecodecamp', function (result) {
    console.log(result);
});

This is because $.getJSON is an asynchronous function, so it returns immediately, while providing its output value through a callback function.

So to get your "return" value, you need to do the same thing i.e. provide a callback to your own function which is invoked when the $.getJSON invokes its own callback.

Upvotes: 2

Related Questions