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

嵌套forEach循环typescript[重复]

  •  1
  • madvic  · 技术社区  · 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 年前