Promises和Deferred:.done()和.then()调用.resolve()在Deferred对象上调用

时间:2016-07-19 23:03:25

标签: javascript jquery html5 promise jquery-deferred

我是Javascript和JQuery的新手。根据我的理解,.then()和.done()是由于对延迟对象的resolve()而触发的。但是在我的代码中,虽然没有调用resolve(),但是触发了.then()和.done()

<head>
    <meta charset="UTF-8">
    <title>Testing Promises</title>
</head>

<body>

<button type="button" onclick="test()"> Click Me</button>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>

    function test() {
        var promise = $.when(another);
        promise.done(function () {
            console.log("another() done");
        });

        promise.done(function () {
            console.log("another() done 2");
        });

        promise.done(function () {
            console.log("another() done 3");
        });

        promise.fail(function (error) {
            console.log("Failed with error = ", error);
        });

        promise.then(function () {
            console.log("In then():");
        });

        console.log("test() done");
    }


    function another() {
        var def = $.Deferred();

        console.log("In another()");
        return def.promise();
    }
</script>

</body>

</html>

2 个答案:

答案 0 :(得分:1)

您正在通过$.when 功能,而不是承诺。它期待着承诺。如果你传递一个承诺(通过实际调用another),你会得到你期望的行为:

&#13;
&#13;
function test() {
  var promise = $.when(another());
  //                          ^^-------------- change is here
  promise.done(function() {
    console.log("another() done");
  });

  promise.done(function() {
    console.log("another() done 2");
  });

  promise.done(function() {
    console.log("another() done 3");
  });

  promise.fail(function(error) {
    console.log("Failed with error = ", error);
  });

  promise.then(function() {
    console.log("In then():");
  });

  console.log("test() done");
}


function another() {
  var def = $.Deferred();
  // Added for testing - start
  setTimeout(function() {
    console.log("waiting...");
  }, 400);
  setTimeout(function() {
    console.log("waiting...");
  }, 800);
  setTimeout(function() {
    console.log("resolving...");
    def.resolve();
  }, 1200);
  // Added for testing - end

  console.log("In another()");
  return def.promise();
}
&#13;
<button type="button" onclick="test()">Click Me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$.when(another)another函数的(立即履行的)承诺。你会想要使用

var promise = $.when(another());

或只是

var promise = another();

实际调用该函数并创建永远无法解析的def