前一段时间我在使用jQuery承诺时遇到了麻烦。在使用.then()函数解决了一系列promise之后,我尝试执行代码。然而,当其中一项承诺遭到拒绝时,它确实无效。 (使用always()函数)
如果我查看官方文档,我会发现:
Then: Description: Add handlers to be called when the Deferred object
is resolved, rejected, or still in progress.
Always: Description: Add handlers to be called when the Deferred
object is either resolved or rejected.
显然,在我的承诺被解决/拒绝的两种情况下,它应该执行当时的回调函数并且始终,但它不会。
有人能解释一下这种行为吗?
以下是fiddle
谢谢大家!
答案 0 :(得分:1)
it should execute the callback functions of then and always, but it doesnt.
在第一个例子中没有附加任何功能来处理被拒绝的承诺。将.fail()
,.always()
添加到.then()
或在.then()
添加第二个参数以处理被拒绝的承诺rjct.reject()
var rslv = $.Deferred();
var rjct = $.Deferred();
var promises = [];
promises.push( rslv );
promises.push( rjct );
$.when.apply( null, promises ).then( function( res ) {
alert( "not finished" );
}
// handle rejected promise
, function( reason ) {
alert( "handle " + reason );
});
rslv.resolve("123");
rjct.reject("rejected promise");
var rslv2 = $.Deferred();
var rjct2 = $.Deferred();
var promises2 = [];
promises2.push( rslv2 );
promises2.push( rjct2 );
$.when.apply( null, promises ).always( function( res ) {
alert( "finished" );
} );
rslv2.resolve();
rjct2.resolve();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>