简体   繁体   English

从JavaScript中的回调返回是否未定义?

[英]Returning from a callback in JavaScript returns undefined?

I've got this code: 我有以下代码:

function fetchSocialCount(type,fileSrc,callback){
    var req = new XMLHttpRequest();
    req.onload = function(){
        if(req.status === 200 && req.readyState === 4){
            var countResponse = JSON.parse(req.responseText);
            callback(countResponse);
        }
    }
    req.open("GET","../scripts/php/returnSocialCount.php",false);
    req.send();
}
var test = fetchSocialCount("img","ez.png",function(count){
    return count;
});

console.log(test);

But for some reason, test is undefined. 但是由于某种原因, test是不确定的。 My AJAX does work, and it returns an object. 我的AJAX确实可以工作,并且它返回一个对象。 What's the problem? 有什么问题?

Your test gets the return value of fetchSocialCount itself, which is undefined since it doesn't return anything. 您的test将获取fetchSocialCount本身的返回值,该值未定义,因为它不返回任何内容。

You can try this: 您可以尝试以下方法:

function fetchSocialCount(type, fileSrc) {
    var req = new XMLHttpRequest()
        , result = null;

    req.onload = function(){
        if(req.status === 200 && req.readyState === 4){
            result = JSON.parse(req.responseText);
        }
    }
    req.open("GET","../scripts/php/returnSocialCount.php",false);
    req.send();

    return result;
}

Since you are using a synchronous request, you should be able to return its result directly; 由于您正在使用同步请求,因此您应该能够直接返回其结果; returning from the callback as you did won't help anyway, in fact, as @Trolleymusic points out in the comments 实际上,正如@Trolleymusic在评论中指出的那样,从回调中返回您仍然没有帮助

the callback returns to that which called the callback, (in this case callback(countResponse) ), no further up 回调返回到称为回调的回调(在本例中为callback(countResponse) ),不再向上移动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM