使用回调函数更改在 getJSON 之外定义的变量的值
Using callback function to change the value of a variable defined outsite of getJSON
好的,所以我有这个功能。
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'));
问题是我在控制台日志中收到的是 "default",而不是 "offline",也不是我预期的 "online, nor "notfound"。
我试图将 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是一个异步函数,所以它returns立即,同时通过回调函数提供它的输出值。
因此,要获得您的 "return" 值,您需要做同样的事情,即为您自己的函数提供回调,当 $.getJSON 调用它自己的回调时调用该函数。
好的,所以我有这个功能。
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'));
问题是我在控制台日志中收到的是 "default",而不是 "offline",也不是我预期的 "online, nor "notfound"。
我试图将 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是一个异步函数,所以它returns立即,同时通过回调函数提供它的输出值。
因此,要获得您的 "return" 值,您需要做同样的事情,即为您自己的函数提供回调,当 $.getJSON 调用它自己的回调时调用该函数。