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

如何使用jquery在另一个函数中返回和使用Ajax调用的值?[副本]

  •  0
  • Yanayaya  · 技术社区  · 4 年前

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

    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 回复  |  直到 2 年前