这个例子说明了我的问题。

$.fn.Heartbeat = function(){
  console.log('started');
  $.ajax({
    url:baseurl.php,
    .
    .
    .
    success: function(data){
      //DO SOME STUFF
      console.log('end of success');
    }
}

$.when($('.mydiv').Heartbeat()).done(function(){console.log('after done');});


此代码输出:

started

after done

end of success

当我想要时:

started

end of success

after done

我的意思是,必须在心跳完成后执行DONE中的函数,否则就不执行。

最佳答案

$.when()不是魔术。它不知道何时将某些函数传递给它。取而代之的是,您必须传递一个承诺,然后它将知道何时完成该承诺。因为您没有从Hearbeat()函数返回诺言,所以$.when()不知道何时实际完成该ajax调用,因此将其视为同步事件。

这是一种更简单的方法:

var Heartbeat = function(){
  console.log('started');
  return $.ajax({
    url:baseurl.php,
    // other args
  }).then(function(data) {
        //DO SOME STUFF
        console.log('end of success');
  });
}

Heartbeat().done(function(){
   console.log('after done');
});


变化:


您必须从心跳中返回承诺,以便.done()可以等待它
无需对单个承诺使用$.when()-只需对该承诺使用.then()
Heartbeat是常规函数(不是jQuery方法),因此您将其称为常规函数。由于该函数不以任何方式使用jQuery对象,因此我看不出有任何理由使其成为jQuery方法。
切换成功处理程序以使用.then(),因为您使用的是Promise
将括号和括号固定为合法JS

10-05 20:30
查看更多