JavaScript:如何在异步内部函数内返回外部函数?

Mel*_*kor 6 javascript ajax jquery closures asynchronous

我知道我可以使用外部变量来识别外部函数需要处理的某些状态.但请考虑一下:如果内部函数是异步的?外部函数不会等待内部函数的变量会改变,那么我现在如何返回外部函数呢?

function outer() {
    var flag = true;
    // For example, a jquery-like ajax call
    $.ajax({
        // Some settings
        error: function(jqXHR, textStatus, errorThrown) {
            // Here I want to return outer()
            flag = false;
        }
    });
    return flag;
}
Run Code Online (Sandbox Code Playgroud)

所以你可以看到,如果我flag用作返回值,outer()很可能会返回true,因为ajax调用可能需要很长时间.出于同样的原因,我不想设置,async: false因为这将停止页面反应.

keu*_*une 7

你的outer功能会立即返回,所以你总会得到trueflag的价值.为了获得正确的值,您需要让异步函数完成其工作并在准备就绪时回复您.考虑一下:

function outer(cb) {
    var flag = true;
    // For example, a jquery-like ajax call
    $.ajax({
        // Some settings
        error: function (jqXHR, textStatus, errorThrown) {
            // Here I want to return outer()
            flag = false;
            cb(flag);
        },
        success: function () {
            flag = true; // or whatever value you need.
            cb(flag);
        }
    });
}

function callback(flag) {
    // this function will be called after the ajax is complete.
    // real value of flag variable will be available here
    console.log(flag);
}
outer(callback);
Run Code Online (Sandbox Code Playgroud)

将函数作为参数传递给外部函数,并在ajax完成时使用您需要的值作为参数调用该函数.这样你就可以得到真实的结果.