我有多個Javascript函數,每個都執行一些DOM操作,然後運行一個ajax請求。我希望能夠運行第一個函數,該函數操縱DOM,然後觸發它的ajax請求,然後,當ajax請求完成時,如果ajax請求返回true,或者要停止執行其他的函數,我想運行第二個函數的功能和做一些其他的DOM操作(如顯示錯誤消息)。如何順序運行多個函數,並在其中任何一個失敗時停止所有函數?
我希望這些函數能夠依次運行,一個接一個地運行,並且只有在它們沒有一個從它們的ajax請求返回false時才繼續運行。如果它們中沒有一個返回false,那麼它們都應該運行,最終我會在我的「始終」回調中進行一些操作。
我該如何做到這一點?
我的第一個想法是使用承諾,以保持代碼更清潔,但經過幾個小時的閱讀,我無法得到如何使這項工作。
下面是我當前的代碼,這就是我得到了我的控制檯,當它執行:
inside test1
inside test2
inside test3
fail
[arguments variable from fail method]
always
[arguments variable from always method]
這是我想在我的控制檯得到(注意失蹤「內TEST3」字符串) :
inside test1
inside test2
fail
[arguments variable from fail method]
always
[arguments variable from always method]
下面的代碼:
(function($) {
var tasks = {
init: function() {
$.when(
this.test1(),
this.test2(),
this.test3()
).done(function() {
console.log('done');
console.log(arguments);
})
.fail(function() {
console.log('fail');
console.log(arguments);
})
.always(function() {
console.log('always');
console.log(arguments);
});
},
test1: function() {
console.log('inside test1');
return $.getJSON('https://baconipsum.com/api/?type=meat-and-filler');
},
test2: function() {
console.log('inside test2');
// note the misspelled "typ" arg to make it fail and stop execution of test3()
return $.getJSON('https://baconipsum.com/api/?typ=meat-and-filler');
},
test3: function() {
console.log('inside test3');
return $.getJSON('https://baconipsum.com/api/?type=meat-and-filler');
}
};
tasks.init();
})(jQuery)
任何想法?
This看起來像我之後...雖然我不確定胖箭頭函數是否支持與常規匿名函數相同的方式?我會嘗試一下,但這看起來非常棒!謝謝你,@Jaromanda X – andrux
'=>'使代碼更加簡潔,而且''this'的更少麻煩:p你總是可以傳遞上面的代碼 –
我把你的代碼轉換成了「常規」的JS,它運行起來,記錄我在控制檯期待的內容:https://gist.github.com/andruxnet/11a0c2baa45e870fc449bac02cb66bf5 – andrux