我是 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>
最佳答案
$.when(another)
是 another
函数的(立即履行的) promise 。您会想要使用
var promise = $.when(another());
或者只是
var promise = another();
实际调用该函数并创建从未解析的def
。
关于javascript - Promises 和 Deferred : . did() 和 .then() 被调用,尽管 .resolve() 在 Deferred 对象上被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38469903/