代码之家  ›  专栏  ›  技术社区  ›  Jasper

Coffeescript:函数未返回Ajax响应[重复]

  •  0
  • Jasper  · 技术社区  · 6 年前

    foo 发出异步请求。如何从返回响应/结果

    我尝试从回调中返回值,并将结果赋给函数内部的一个局部变量并返回该变量,但这些方法都没有真正返回响应(它们都返回 undefined 或者变量的初始值 result 是)。

    使用jQuery的示例 ajax

    function foo() {
        var result;
    
        $.ajax({
            url: '...',
            success: function(response) {
                result = response;
                // return response; // <- I tried that one as well
            }
        });
    
        return result; // It always returns `undefined`
    }
    

    示例使用js节点:

    function foo() {
        var result;
    
        fs.readFile("path/to/file", function(err, data) {
            result = data;
            // return data; // <- I tried that one as well
        });
    
        return result; // It always returns `undefined`
    }
    

    示例使用 then 承诺块:

    function foo() {
        var result;
    
        fetch(url).then(function(response) {
            result = response;
            // return response; // <- I tried that one as well
        });
    
        return result; // It always returns `undefined`
    }
    
    0 回复  |  直到 4 年前