使用回调函数更改 getJSON 外部定义的变量的值

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

本文关键字:定义 外部 变量 getJSON 回调 函数      更新时间:2023-09-26

好的,所以我有这个函数。

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'));

问题是我在控制台日志中收到的是"默认",而不是"离线",也不是"在线",也不是我预期的"未找到"。

我试图在 check() 函数之前移动 console.log() 行,但它不起作用。我还尝试全局定义 var 结果,但它也不起作用。

任何帮助将不胜感激!

这是

你的代码应该如何编写:

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);
});

这是因为 $.getJSON 是一个异步函数,因此它会立即返回,同时通过回调函数提供其输出值。

因此,要获得您的"返回"值,您需要做同样的事情,即提供对您自己的函数的回调,当 $.getJSON 调用自己的回调时调用该函数。