I want to wait all callback functions finish and then return a final result, like this:
var jsonArray = new Array();
for(var i = 0; i < 10; i++)
{
jQueryFunction(i, function(json){
jsonArray[i] = json;
});
}
return jsonArray;
jQueryFunction is a function which contains the asynchronous ajax and callback, return a value which is called json. I want to wait for the for loop finish and then put all the return values into jsonArray, return it finally.
My goal is that waiting for all jQueryFunction callbacks finish and store their return into jsonArray, and then return jsonArray at the end. My previous goal doesn't work because it returns the jsonArray right away and doesn't wait for the for loop
I tried like this:
function jQueryFunction(ptd_url, callback)
{
$.ajax
({
type: "GET",
async: true,
url: ptd_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
return callback(json);
}
});
}
function finalResultFunction()
{
var jsonArray = new Array();
for(var i = 0; i < 10; i++)
{
jQueryFunction(1, function(json){
jsonArray[i] = json;
alert(jsonArray[i]);
});
}
$.when.apply($, jsonArray).done(function(){
alert(jsonArray[0]);
...
}
setInterval(finalResultFunction,1000);
The first alert shows me the correct object, but the second one still shows me null. Why? How to fix it?