我需要一個方法來獲取不同的腳本與回調。 此方法確定:
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');
})
},
,但我想更概括的方法,因爲redundany增加。 是否可以將承諾傳遞給$ .when()? 下面我第一次嘗試 - 但URL始終是相同的,即「腳本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();
},
要訪問您可以使用傳遞給'.then'匿名函數內部的'arguments'魔術變量遞延值的結果; –
我注意到在使用then()時,如果有任何請求失敗,儘管沒有完成所有的任務,但是您將輸入它的函數,而done()只會在最後一個要完成時纔會執行,不管是否有失敗。 –