小编典典
IMO jQuery.Deferred()目标将是最有希望的方式。
Deferred对象是chainable utility通过调用jQuery.Deferred()方法创建的对象。它可以将多个回调注册到回调队列中,调用回调队列,并中继任何同步或异步功能的成功或失败状态。
deferred objects可用于处理异步事件-您启动一个动作,然后注册一个回调,该回调将在动作完成时调用。这包括AJAX,尽管还有很多其他用途。
哪里要求解决
function callAjaxMethod(url, step) {
return $.Deferred(function() {
//Confirm box for use inputs
if(confirm(step))
{
//Ajax call
$.ajax(url).done(function(data){
//Do something
//Update your HTML if needed
});
}
setTimeout(function() {
//This will resolve your call again
this.resolve();
}.bind(this), 1000);
})
}
递延对象
var defer = $.Deferred().resolve();
var counters = [1, 2, 3, 4, 5];
$.each(counters, function(key, value) {
defer = defer.then(function() {
return callAjaxMethod('URL', value);
});
});
完成后它将调用
defer.then(function() {
//It will call when all done
});
很少的文档
希望这对您有帮助:)
var $demo = $('#demo');
var ajaxURL = 'https://jsonplaceholder.typicode.com/posts';
function callAjaxMethod(url, step) {
return $.Deferred(function() {
//Confirm box for user inputs
if(confirm(step))
{
//Ajax call
$.ajax(url).done(function(data){
//Do something
//console.log(data);
//Update the HTML OK
$demo.append(step + ": Success" + "
");
});
}
else
{
//Update the HTML when cancel
$demo.append(""+ step +": Cancelled " + "
");
}
//Use timeout to get the resolved
setTimeout(function() {
this.resolve();
}.bind(this), 1000);
})
}
//Defer object
var defer = $.Deferred().resolve();
var counters = ['call 1', 'call 2', 'call 3', 'call 4', 'call 5'];
//Loop your calls
$.each(counters, function(key, value) {
defer = defer.then(function() {
return callAjaxMethod(ajaxURL, value);
});
});
defer.then(function() {
//It will call when all done
$(demo).append("
"+"ALL DONE");
});
div
{
color: blue;
font-size: 14px;
}
2020-07-26