Mar*_*.io 4 javascript ajax jquery jquery-deferred
在这个问题上真的很难,而且我知道$.when()可以这样使用(有多个AJAX语句)来保证你完成它们的时候.
$.when(
$.ajax({ url: '/echo/html/', success: function(data) {
alert('request 1 complete')
}
}),
$.ajax({ url: '/echo/html/', success: function(data) {
alert('request 2 complete')
}
})
).then( function () { alert('all complete'); });
Run Code Online (Sandbox Code Playgroud)
但这只适用于raw $.ajax(),无论如何都有与函数调用相同的功能,反过来它们内部的ajax(以及其他随机逻辑)?
伪代码的想法:
// The functions having the AJAX inside them of course
$.when(ajaxFunctionOne, ajaxFunctionTwo).then(function () {
alert('all complete');
});
Run Code Online (Sandbox Code Playgroud)
当然,让函数返回一个promise对象.
function ajaxFunctionOne() {
return $.ajax(...)
}
function ajaxFunctionTwo() {
var dfd = $.Deferred();
// on some async condition such as dom ready:
$(dfd.resolve);
return dfd.promise();
}
function ajaxFunctionThree() {
// two ajax, one that depends on another
return $.ajax(...).then(function(){
return $.ajax(...);
});
}
$.when(ajaxFunctionOne(),ajaxFunctionTwo(),ajaxFunctionThree()).done(function(){
alert("all complete")
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
612 次 |
| 最近记录: |