$ .when.then()执行的jQuery序列

时间:2017-02-21 19:10:51

标签: javascript jquery

我正在尝试按特定顺序执行函数,但在理解$.when()时遇到了问题。



function x() {
  def = $.Deferred();
  $.when(def).then(console.log(def.state()));
}
x();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
&#13;
&#13;
&#13;

我的理解是,当def解决后,console.log(def.state())应该执行。换句话说,由于x()defpending执行{{1}}时,我不应该得到任何回报吗?

2 个答案:

答案 0 :(得分:3)

then需要回调,因此您应该创建一个wrap函数:

function x() {
  def = $.Deferred();
  $.when(def).then(function(){
    console.log(def.state())
  });
}
x();

答案 1 :(得分:1)

首先:您应该解决Deffered。第二:你应该将一个函数传递给then方法。

function x() {
  def = $.Deferred().resolve();
  $.when(def).then(function () {
    console.log(def.state());
  });
}
x();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>