如何从 JavaScript 中的嵌套函数处理程序 return?

How to return from a nested function handler in JavaScript?

我有这个代码:

function fetchSocialCount(type,fileSrc){
    var count = {likes: 0, dislikes: 0};
    var req = new XMLHttpRequest();
    req.onload = function(){
        if(req.status === 200 && req.readyState === 4){
            var countResponse = json_encode(req.responseText);
            count.likes = countResponse.likes;
            count.dislikes = countResponse.dislikes;
            return count;
        }
    }
}

所以,我想从 req.onload 函数表达式 return count,就好像它是 return 从 fetchSocialCount 函数编辑的一样。我怎样才能做到这一点?

req.onload 是异步的。您需要使用回调、承诺或类似的东西来获得结果 "count"

function fetchSocialCount(type,fileSrc, cb){
    var count = {likes: 0, dislikes: 0};
    var req = new XMLHttpRequest();
    req.onload = function(){
        if(req.status === 200 && req.readyState === 4){
            var countResponse = json_encode(req.responseText);
            count.likes = countResponse.likes;
            count.dislikes = countResponse.dislikes;
            cb(count);
        }
    }
}

//calling fetchSocialCount
fetchSocialCount(my_type, my_file_src, function(count){
    //here it is
    console.log(count);
});