JQuery Ajax: how to wait until * async * finishes executing queries before continuing?

I have a problem with fast and functional ajax work. Here's the pseudo / prototype code:

function blah1(arg1){//arg1 is an array, roughly 10 elements var arr[]; $.each(arg1, function(i){ //blah code $.ajax({ //blah options async: true, success: function(data){ arr[i] = data.someInt; }//end success });//end ajax }//end each return arr; }//end function 

Basically, I send ajax and need the returned data for further processing.

If I set async to true, the function immediately returns an empty arr array, so the whole script fails. But if I set async to false, then it works, but it takes a very long time.

I saw this $. ajaxQueue (); thing, but frankly, I don’t understand it at all, and I don’t know if it will work.

So, the question is, firstly, is there a way to send all ajax requests asynchronously at the same time and allow the wait and return arr [] functions after all ajax is complete? If not, will ajaxQueue work in my case? (an example?)

+7
source share
2 answers

Using jQuery 1.5 delayed, I would choose 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 that you tried to return the array to your function before completing the asynchronous aynax calls. This is really not possible, so you will need to pass the blah callback.

What you are doing here is mapping your array of objects to jqXHR objects (which are pending objects). Then we pass this array of pending objects to $.when .

$.when takes an array and then lets you run the .then function when the whole array has finished loading from ajax calls. Then you pass resultsArr as an argument to your .then function.

It is not possible to use $.ajax and return in the same function if you control the return value in your ajax success call.

+5
source

You can make a synchronous Ajax call, which you seem to know about, personally I would rephrase my code to use the success method of an ajax call, and then call another function call.

 $.ajax({ //blah options async: true, success: function(data){ arr[i] = data.someInt; myCall(arr[i]); }//end success });//end ajax 
+4
source

All Articles