Javascript-迭代数组并调用Jquery Ajax请求并等待请求完成,然后再移至下一个请求? [英] Javascript - Iterate an array and call Jquery Ajax requests and wait for a request finished before moving to next request?
问题描述
我需要迭代一个数组(或简单的for循环)以向服务器运行Ajax请求.问题是,要运行下一个元素,当前的Ajax请求必须首先完成.
I need to iterate an array (or a simple for loop) to run Ajax request to a server. The problem is, to run next element, current Ajax request must finish first.
到目前为止,我已经尝试过这种方法,但是它无法正常工作,因为它似乎没有等待1个Ajax请求完成才移至下一个请求.我以为承诺和然后可以做到,但事实并非如此.
I've tried so far like this but it does not work as it seems it does not wait for 1 Ajax request finished before moving to the next request. I thought promise with then can do it but it is not.
var ajax = function(rasqlQuery) {
return new Promise(function(resolve, reject) {
var getURL = "http://test" + "?username=rasguest&password=rasguest&query=" + encodeURIComponent(rasqlQuery);
$.ajax({
url: getURL,
// Not using async: false here as the request can take long time
type: 'GET',
cache: false,
timeout: 30000,
error: function(error) {
alert("error " + error.statusText);
},
success: function(result) {
resolve(result) ;
}
});
});
}
var promise;
for (var i = 0; i < 10; i++) {
// It should send Ajax request and wait the request finished before running to next iteration.
// Or if not possible, it can register 10 requests but they must be run sequentially.
promise = ajax("select 1 + " + i).then(function(result) {
console.log("i: " + i);
console.log("Result: " + result);
});
}
推荐答案
Promise是一个异步操作,因此与其在循环中发布它,不如将其链接在一起,只需说下一次提取应在( .then
)上一个完成:
Promise is an async operation, so instead of issuing it in the loop, you need to chain them together, by saying that the next fetch should only happen after (.then
) previous one finishes:
var promise = Promise.resolve();
for (var i = 0; i < 10; i++) {
// You need to use this IIFE wrapper or ES2015+ let otherwise printed `i`
// will always be 10 because interaction between async behavior and closures
(function (i) {
promise = promise.then(function () {
return ajax("select 1 + " + i).then(function(result) {
console.log("i: " + i);
console.log("Result: " + result);
})
})
})(i);
}
promise.then(function () {
console.log("all done");
})
这篇关于Javascript-迭代数组并调用Jquery Ajax请求并等待请求完成,然后再移至下一个请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!