【问题标题】:JavaScript: How to return an outer function inside an asynchronous inner function?JavaScript:如何在异步内部函数中返回外部函数?
【发布时间】:2014-05-27 08:53:00
【问题描述】:

我知道我可以使用外部变量来识别外部函数需要处理的某些状态。但是考虑一下:如果内部函数是异步的?外层函数不会等到内层函数的变量发生变化,那现在怎么才能返回外层函数呢?

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;
}

如您所见,如果我使用flag 作为返回值,outer() 很可能会返回true,因为ajax 调用可能需要很长时间。出于同样的原因,我不想设置async: false,因为这会阻止页面反应。

【问题讨论】:

  • 异步流无法做到这一点,我建议您在 ajax 请求完成时调用 outer(cb) 的参数作为参数。
  • 是的,你是对的,我想错了。

标签: javascript jquery ajax asynchronous closures


【解决方案1】:

您的outer 函数将立即返回,因此您将始终将true 作为flag 的值。为了获得正确的值,您需要让 async 函数完成它的工作,并在它准备好时回复您。考虑一下:

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);

您将一个函数作为参数传递给外部函数,当 ajax 完成时,它会调用该函数,并使用您需要的值作为参数。这样你就会得到真正的结果。

【讨论】:

  • 谢谢,但我确实需要立即退货。现在我意识到它和async: false 一样。所以我会找到其他方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 2016-03-30
  • 2023-02-23
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
相关资源
最近更新 更多