jQuery延期:取消进度 [英] jQuery deferred: cancel progress
问题描述
有没有办法取消正在进行的延迟回调队列?
我有任意数量的ajax调用。当成功数据返回特定标记时,我想停止进一步的ajax请求:
Is there a way to cancel a deferred callback queue in progress? I have an arbitrary amount of ajax calls. I'd like to stop further ajax requests when data of success returns specific marker:
this.oDeferred=$.Deferred();
this.oChain=this.oDeferred;
for(var i=0; i<this.aKey.length; i++) {
(function(iKey,self) {
self.oChain=self.oChain.then(function(){
return $.ajax({
url:self.aUrl[iKey],
type:'post',
data:{'ajax':true},
dataType:'json',
success:function(data) {
if(data.bCancel==true) {
//stop deferred object here!
}
}
});
})
}(this.aKey[i],this))
}
this.oDeferred.done(function() {
console.log('done')
});
this.oDeferred.resolve()
顺便说一下 - 函数done()是所有ajax请求发出后都会自动触发。所有ajax请求完成后如何执行函数?
By the way - the function done() is fired autonomous after all ajax requests are made. How to execute a function after all ajax requests are done?
提前谢谢!
推荐答案
答案是肯定的。有两种方法。
The answer is yes. Two approaches are possible.
.then()
方法返回一个新的promise,其状态由传递给方法的处理程序返回的内容决定。
The .then()
method returns a new promise, the state of which is determined by what is returned from the handler(s) passed to the method.
- 通过返回一个非承诺的值/对象,新的承诺沿着方法链向下传递,其具有与原始承诺相同的已解决/拒绝状态,但使用返回的值/对象解析/拒绝。
- 通过返回一个承诺,该承诺传递给方法链,其状态独立于原始承诺。
因此,通过从 .then()
处理程序返回一个永远不会解决的承诺,从而可以有效地取消Deferred / promise回调队列被拒绝。这样的承诺可以从 .then()
处理程序的done处理程序(第一个参数)或其失败处理程序(第二个参数)中进行。 .done()
, .fail()
或 .always无法实现同样的效果。 ()
方法,返回原始Deferred / promise而不进行修改。
Thus, Deferred/promise callback queue can be effectively canceled by returning from a .then()
handler a promise that is never resolved and never rejected. Such a promise can be made from the .then()
handler's done handler (first argument) or its fail handler (second argument). The same cannot be achieved with .done()
, .fail()
or .always()
methods, which return the original Deferred/promise without modification.
在 .then()中抛出未被捕获的错误
, .done()
, .fail()
, .always()
或 .progress()
handler将通过终止正在运行的事件线程来终止方法链。
An uncaught error thrown from within a .then()
, .done()
, .fail()
, .always()
or .progress()
handler will kill a method chain by killing the event thread in which it is running.
可以故意抛出错误,例如 throw('故意错误')
。
An error can be thrown deliberately with eg throw('deliberate error')
.
应该注意的是,这两种方法都只能抑制链式方法处理程序(或通过赋值实现的等效处理)。
It should be noted that both approaches will only suppress chained method handlers (or the equivalent achieved by assignment).
无论使用哪种方法,在执行抑制返回/错误表达式时已经启动的任何异步进程都将继续,并且任何相应的已完成/失败/始终/进度处理程序可能已经启动。
With either approach, any asynchronous process that is already initiated at the point the suppressing return/error expression executes will continue and any corresponding done/fail/always/progress handler already in place may fire.
这篇关于jQuery延期:取消进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!