I\'m having a problem making ajax fast and functional. Here\'s the pseudo/prototype code:
function blah1(arg1){//arg1 is an array, roughly 10 elemen
You could make the Ajax call synchronous which you seem to know about, personally I would re factor my code so the success method of the ajax call, then triggers a call off to another function.
$.ajax({
//blah options
async: true,
success: function(data){
arr[i] = data.someInt;
myCall(arr[i]);
}//end success
});//end ajax
Using jQuery 1.5 deferred's I would opt for this :
function blah1(arr, callback){
$.when($.map(arr, function(val, i){
$.ajax({
//blah options
async: true
});
}).toArray()).then(function(resultsArr) {
callback(resultsArr);
});
}
The problem was you were trying to return the array in your function before the async ajax calls finish. This isn't really possible so you will need to pass a callback to blah.
What your doing here is mapping your array of objects to jqXHR objects (which are deferred objects). Then passing that array of deferred objects to $.when
.
$.when
takes an array and then allows you to run the .then
function when the entire array has finished loading from the ajax calls. You then have a resultsArr
passed in as an argument to your .then
function.
There is no way to use $.ajax
and return
in the same function if you manipulate the return value in your ajax success call.