jQuery Ajax: how to wait until *async* requests success completes before continuing?

后端 未结 2 982
日久生厌
日久生厌 2021-01-12 12:50

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         


        
相关标签:
2条回答
  • 2021-01-12 13:04

    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
    
    0 讨论(0)
  • 2021-01-12 13:15

    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.

    0 讨论(0)
提交回复
热议问题