[英]alternative to async: false ajax
I loop through an array running an ajax request for each. 我遍历一个运行ajax请求的数组。 I need the requests to happen in order, so i can pick up the last request and run a function on success. 我需要按顺序发生请求,所以我可以获取最后一个请求并在成功时运行一个函数。
at the moment im running (simplified): 目前我正在运行(简化):
$.each(array, function(i, item){
ajax_request(item.id, item.title, i);
})
function ajax_request(id, title, i){
$.ajax({
async: false,
url: 'url here',
success: function(){
if(i == array.length-1){
// run function here as its the last item in array
}
}
})
}
however, using async:false makes the application unresponsive/ slow. 但是,使用async:false会使应用程序无响应/缓慢。 but, without async:false sometimes one of the requests will hang a bit and actually return after the last sent ajax request returns. 但是,没有async:false有时其中一个请求会挂起一点,并在最后发送的ajax请求返回后实际返回。
how can i implement this without using async:false ? 如何在不使用async的情况下实现这一点:false?
You can use a local function for running the ajax call and in each successive success handler, you can kick off the next ajax call. 您可以使用本地函数来运行ajax调用,并且在每个连续的成功处理程序中,您可以启动下一个ajax调用。
function runAllAjax(array) {
// initialize index counter
var i = 0;
function next() {
var id = array[i].id;
var title = array[i].title;
$.ajax({
async: true,
url: 'url here',
success: function(){
++i;
if(i >= array.length) {
// run function here as its the last item in array
} else {
// do the next ajax call
next();
}
}
});
}
// start the first one
next();
}
Updating this answer in 2016 with an option that uses promises. 使用promises选项在2016年更新此答案。 Here's how you run the requests in series: 以下是您按顺序运行请求的方式:
array.reduce(function(p, item) {
return p.then(function() {
// you can access item.id and item.title here
return $.ajax({url: 'url here', ...}).then(function(result) {
// process individual ajax result here
});
});
}, Promise.resolve()).then(function() {
// all requests are done here
});
Here's how you run them in parallel, returning all the results: 以下是您并行运行它们的方法,返回所有结果:
var promises = [];
array.forEach(function(item) {
// you can access item.id and item.title here
promises.push($.ajax({url: 'url here', ...});
});
Promise.all(promises).then(function(results) {
// all ajax calls done here, results is an array of responses
});
您可以将AJAX代码放在一个单独的函数中,每当请求完成时,它都可以调用此方法并传递其标识,该标识将在下一个请求时递增。
Try $.when() 试试$ .when()
var requests = $.map(array, function (i, item) {
return ajax_request(item.id, item.title, i);
});
$.when.apply($, requests).done(function(){
$.each(arguments, function(i, params){
var data = params[0];
//do your stuff
})
})
function ajax_request(id, title, i) {
return $.ajax({
async: false,
url: 'url here'
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.