我正在尝试调用一些像这样的异步函数。为什么在案例A和案例B中我失败了,但在案例C中却成功了?
案例A
firstCall()// try to get esstential parameters(a defered)
.fail(function(){
//failed :call login function again wait user to input login credential(also a defered)
})
.always(function() {
//show welcome message
})
在这种情况下,当fail刚开始执行时,always部分就直接执行,无需等待。
情况B
firstCall()// try to get esstential parameters(a defered)
.fail(function(){
//failed :call login function again wait user to input login
})
.done(function() {
//show welcome message
})
在这种情况下,如果fail部分被执行,但done部分永远不会被执行。
案例C
firstCall()// try to get esstential parameters(a defered)
.then(null,function(){
//failed :call login function again wait user to input login
})
.always(function() {
//show welcome message
})
在这种情况下,then
部分充当失败部分,并且始终可以在then
完成后运行。
我不确定为什么会发生这种情况。有人可以进一步解释吗?谢谢
最佳答案
此答案中的所有外部引用均取自 jQuery Deferred Object documentation或其中链接的相应方法文档。
<小时/>案例A
"...the always part just execute without waiting."
让我们看一下 .fail()
的文档:
...
deferred.fail()
returns the deferred object, other methods of the deferred object can be chained to this one...
.fail()
方法返回原始延迟对象,而不是打开一个新的 Promise。这意味着链接到它的任何事件虽然将按顺序运行,但本质上不会等待前面的事件完成。您的 .fail()
不会被等待,而是立即执行。
您想要附加的任何回调方法都必须链接到内部函数,从而创建延迟对象的嵌套循环 - 您可以想象如果我们开始深入三到四个回调,情况会变得多么难看。
幸运的是,.then()
就是为了这个目的而存在的! 但在案例 C 中对此有更多了解...
情况 B - “在这种情况下,如果失败部分被执行,但完成部分永远不会被执行。”
.done()
和 .fail()
是相反。对于任何单个延迟对象,只有其中一个会根据它是成功还是失败而触发。
deferred.done()
Add handlers to be called when the Deferred object is resolved.
<小时/>
deferred.fail()
Add handlers to be called when the Deferred object is rejected.
案例C
.then()
Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
.then()
和 .fail()
都处理拒绝的延迟对象。
但是有一个主要区别:
As of jQuery 1.8, the
deferred.then()
method returns a new promise...
.then()
返回一个新的 Promise,而 .fail()
则不会。这意味着链接到 .then()
方法的任何方法都将等待其完成,就像原始延迟对象一样。
摘要:
如果您尝试进行连续的等待调用,请使用.then()
。这将允许您以一系列新的 Promise 的形式在链中前进,同时保持原始延迟对象的状态和值。
如果您完成了顺序调用并且准备好“关闭”延迟对象,请使用返回延迟对象的方法,例如 .done()
、。 fail()
或.always()
。
关于jquery - jquery延迟调用的这些模式有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47233661/