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.
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);
});
}