Search code examples
ajaxjsonp

Need to access variable after all ajax call completed


I setup an ajax call in a loop.

 while (true) {


            doAjax("GET", "api", "jsonp");

            if (startDate.valueOf() == endDate.valueOf()) {

                break;
            }

            startDate.setDate(new Date(startDate.getDate() + 1));
        }

Where the ajax function is defined as

function doAjax(methodType, url, responseDataType) {

    var options = {
        type: methodType,
        url: url,
        dataType: responseDataType,

    };

    $.ajax(options).done(function (data) {

        postData.push(data);

    }).fail(function (response) {
        console.log(response);
    });
};

Currently, when all successful call has been made, I finally have an array 'postData' which contain the results of all calls.

Now I am wondering how can I access that variable after all ajax call get's finished. As you can see all happening in the loop, how can I figure out when final ajax call has been made.

Any suggestion?


Solution

  • There's no way to know when the async call completes aside from handling the success (done) or error (fail). So, instead of handling done()/fail() inside of the doAjax() function simply return a promise:

    return $.ajax(options); //remove the done() and fail() code
    

    Then in the function that calls the doAjax function handle the done() and fail().

    doAjax("GET", "api", "jsonp").done(...).fail(...);