Friend the ajax requests are asynchronous, which means you do not know when the response lasts.
That's why the for
if you execute the requests but the variable i
gets it back after the time it took to go and make the request so i
is worth 10
because the time of the for
is much faster than that of each request within the.
I hope you help greetings.
NOTE : A test API was used to make the query.
Example
var root = 'https://jsonplaceholder.typicode.com';
for(var i = 0; i < 10; i++) {
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
console.log(i);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Solution
If you want you can do a cursive function that only runs when you return the ajax would be like your own for
The idea is to execute the ajax and that when returning, call the same function but with the condition variable with a number until it is fulfilled and Ajax is not executed anymore.
Functional example
var root = 'https://jsonplaceholder.typicode.com';
var numero = 0
function miFor(numero){
if(numero<10){
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
console.log(numero);
numero++
miFor(numero)
});
}
}
miFor(0)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>