I'm new to ajax and JavaScript. What am trying to do is to call an ajax function several times to fetch certain data from a resource and then "push" all of the data into an array so that I can use it later on in the code. Here is my code.
var arr = [];
var users = ["brunofin", "comster404", "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for (i = 0; i < users.length; i++) {
$.ajax({
url: "https://api.twitch.tv/kraken/streams/" + users[i],
success: function(data) {
arr.push(data);
},
error: function(data) {
arr.push("blank");
},
complete: function() {
if (i == users.length) {
console.log(arr); //This seem to print even when the condition isn't true
}
}
});
}
The problem with the code is that, it prints to the console even when i
isn't equal to users.length
My question is; how do I make certain that it waits until i == users.length
is true before it prints to the console?
Please keep in mind that I still desire the process to be asynchronous.
you can try by calling ajax with async false as below
This happens because of the asynchronous nature. By the time the ajax callbacks are called,
i == user.length
is already true. But in your case you can just change:to:
This will also work nice if the callbacks are not executed in the same order as you initiated the ajax requests.
Can you try below code:
Try Below code it's working fine.
Please have look below code wihout loop and asyns:false, tested working fine.
The easiest way is to use a closure. Whenever you have something asynchronous in a loop, it is the same thing.
In this pseudocode snippet, the inner function captures the storage location referenced by i. The loop runs, the i increments to its final value, and then the async callbacks start getting called, all of them looking up the exact same location (not value).
The general solution is this:
i.e. wrap the whole contents of your loop in an self-executing function.
Here, the value of outer i gets passed into the wrapping self-executing anonymous function; this unique value's location gets captured by the async callback. In this way, each async gets its own value, determined at the moment the self-executing function is invoked.
Here is how you can call all requests considering their success without running an request over another:
Working demo