I'm trying to read in several urls as text and store them into an array with jquery's ajax/get. I need to wait for all data to be obtained (and pushed to an array) and then return it in a function. From what I read online, this isn't possible.
I figured if I set a global array variable and pushed into that every time new data is obtained, then checked using a while loop if the array is saturated, when it is return. See below
You can assume all errors are handled within the get
call
function fetchData(){
x = [1,2,3,4,5,6,7,8,9,10];
a = [];
//Loop, get and push data
$.each(x, function( i, val ) {
$.get("http://someurl/"+i, function( data ) {
a.push(data);
});
});
// Wait till our array is populated?
while(a.length < x.length){
console.log(a.length);
}
return a;
}
However, this approach does not seem to be working and nothing is ever added to the array.. Can someone point me in the right direction?
Thank you