我已经阅读了十几次,因为状态对象可能存在多个键值对,并且它与新的历史条目相关联.但有人可以给我一个状态对象的好处的例子吗?它的实际用途是什么?我无法想象为什么不只是输入{}
有没有办法取消正在进行的延迟回调队列?我有一个任意数量的ajax调用.当成功数据返回特定标记时,我想停止进一步的ajax请求:
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()
Run Code Online (Sandbox Code Playgroud)
顺便说一句 - 在完成所有ajax请求后,函数done()将被自动触发.所有ajax请求完成后如何执行函数?
先感谢您!
我需要一种方法来使用回调来获取不同的脚本.这种方法可行:
fetchScripts:function() {
var _this=this;
$.when(
$.ajax({
url:_this.url + 'library/script-one.js',
type:'get',
cache:true
}),
$.ajax({
url:_this.url + 'library/script-two.js',
type:'get',
cache:true
}),
{ .... },
$.ajax({
url:_this.url + 'library/script-n.js',
type:'get',
cache:true
})
).then(function() {
console.log('fetch is done');
})
},
Run Code Online (Sandbox Code Playgroud)
但我想更加概括该方法,因为冗余正在增加.是否有可能将承诺传递给$ .when()?低于我的第一次尝试 - 但是网址总是相同的,即'script-n.js'也许我错过了这一点,你可以说明一个更"美"的解决方案
fetchScripts:function() {
this.deferred=new $.Deferred();
this.promise=this.deferred.promise();
var _this=this;
$.each([
'script-one.js',
'script-two.js',
( .... ),
'script-n.js'
],function() {
_this.script=this;
_this.promise.then(function(){
return $.ajax({
url:_this.url + 'library/' + _this.script,
type:'get',
cache:true
})
});
});
$.when(
this.promise
).then(function() {
console.log('fetch is done');
});
this.deferred.resolve(); …Run Code Online (Sandbox Code Playgroud)