[英]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. 我试图将console.log()行移到check()函数之前,但是它不起作用。 I also tried to define the var result globally but it doesn't work either. 我还尝试了全局定义var结果,但是它也不起作用。
Any help would be appreciated ! 任何帮助,将不胜感激 !
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. 这是因为$ .getJSON是一个异步函数,因此它立即返回,同时通过回调函数提供其输出值。
So to get your "return" value, you need to do the same thing ie provide a callback to your own function which is invoked when the $.getJSON invokes its own callback. 因此,要获得“返回”值,您需要做同样的事情,即为您自己的函数提供一个回调,该回调在$ .getJSON调用其自己的回调时被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.