【问题标题】:jquery - do something after everything is done -jquery - 一切完成后做一些事情 -
【发布时间】:2013-05-16 03:40:42
【问题描述】:

我有一组函数要按顺序运行,但第一个函数有一个异步子函数。我希望第二个最高级别的函数仅在异步函数完成后运行。知道我该怎么做吗?

文件 A:

one();
two(); // I don't want this to run until after one()'s $.ajax success callback

function one() {
    doSomethingElse();
    $.ajax(url, {data: data}, function(){
        // do two();
    });
}

【问题讨论】:

  • 为什么不直接在$.ajax 的success 方法中调用two()?
  • 如果您不希望它异步运行,也可以将 async: false 添加到您的 ajax 调用中。

标签: javascript jquery jquery-deferred promise


【解决方案1】:

更改您的函数以返回 AJAX 对象:

function one() {
    doSomethingElse();

    return $.ajax({
        url: url,
        data: data
    });
}

现在你可以这样做了:

one().done(function() {
    two();
});

这比将two() 直接放入回调中要干净一些。

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:
      function one() {
          doSomethingElse();
          $.ajax(url, {data: data}, function(){
              // do two();
              two();
          });
      }
      
      function two(){
      alert("here");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 2011-10-09
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多