好的,所以我有这个功能。
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'));
问题是我在控制台日志中收到的内容是“默认”,而不是“离线”,也不是“在线”,也不是我期望的“未找到”。
我尝试将 console.log() 行移到 check() 函数之前,但它不起作用。我还尝试全局定义 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 调用其自己的回调时调用。
关于javascript - 使用回调函数更改在 getJSON 外部定义的变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34866502/