【问题标题】:How to return from a nested function handler in JavaScript? [duplicate]如何从 JavaScript 中的嵌套函数处理程序返回? [复制]
【发布时间】:2016-01-04 22:41:07
【问题描述】:

我有这个代码:

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 函数表达式返回count,就好像它是从fetchSocialCount 函数返回的一样。我怎样才能做到这一点?

【问题讨论】:

  • “我怎样才能做到这一点?” 你不能。就像你必须为onload 分配一个函数来获得响应一样,fetchSocialCount 的调用者必须将一个函数传递给fetchSocialCount(或类似的东西)。这是 Stack Overflow 上被问到最多的 JavaScript 问题之一。

标签: javascript function return nested-function


【解决方案1】:

req.onload 是异步的。您需要使用回调、promise 或类似的东西来获取结果“计数”

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);
});

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 2011-03-23
    • 2011-03-31
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 2021-04-15
    • 2015-07-20
    相关资源
    最近更新 更多