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

如何从非异步函数调用异步函数[重复]

  •  -1
  • user3587624  · 技术社区  · 3 年前

    如何返回函数的响应/结果 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`
    }
    

    使用Node.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 年前
    推荐文章