rps*_*ep2 4 javascript ajax jquery
我遍历一个运行ajax请求的数组.我需要按顺序发生请求,所以我可以获取最后一个请求并在成功时运行一个函数.
目前我正在运行(简化):
$.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
}
}
})
}
Run Code Online (Sandbox Code Playgroud)
但是,使用async:false会使应用程序无响应/慢.但是,没有async:false有时其中一个请求会挂起一点,并在最后发送的ajax请求返回后实际返回.
如何在不使用async的情况下实现这一点:false?
您可以使用本地函数来运行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();
}
Run Code Online (Sandbox Code Playgroud)
使用promises选项在2016年更新此答案.以下是您按顺序运行请求的方式:
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
});
Run Code Online (Sandbox Code Playgroud)
以下是您并行运行它们的方法,返回所有结果:
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
});
Run Code Online (Sandbox Code Playgroud)