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

后端 未结 2 980
日久生厌
日久生厌 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: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.

提交回复
热议问题