我需要进行一系列 AJAX 调用(对不同的 URL),然后仅在所有调用完成后才进行另一系列调用。到目前为止我的代码:
(function (delay) {
var toDo = 10, // for example
curr = 0;
process = setInterval(function() {
// do a call
// blahblahblah
// then:
if(curr === toDo) {
clearInterval(process);
} else {
curr++;
}
}, delay);
})(2000);
// repeat for the 2nd series, but this code will execute immediately since they are async
我使用这种格式而不是简单的 for
循环的原因是我需要在每次调用之间暂停。在第一个系列全部完成之前,我无法启动第二个系列,因为这是我获取第二个系列的 URL 的地方;所以我不能将所有调用都放入同一个自调用函数中。我需要在第一个系列完成后仅执行第二个系列。
最佳答案
假设使用 jQuery,您应该能够使用 Promise 来做到这一点:
$.when( // first set
$.ajax({}),
$.ajax({})
).then(function(){ // second set
$.ajax({});
$.ajax({});
});
关于javascript - 进行两个系列的异步调用,中间有延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32168294/