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

如何在node js中实现流同步?[副本]

  •  0
  • TechChain  · 技术社区  · 5 年前

    我有一个功能 foo 发出异步请求。如何从返回响应/结果 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 回复  |  直到 3 年前