Search code examples
javascriptjqueryajaxiife

execute code after AJAX loop finished


I have an AJAX call that gets called "i" amount of times. I want to execute the rest of the code only after the last AJAX processData callback function was finished (It fills values of the .csv into an array called "lines" and I need the finished array after all iterations have finished). So far it only works by using "setTimeout()" which is not a nice solution

for (var i = 0; i < options.length; i++) {
    (function(index) {
        $.ajax({
            type: "GET",
            url: options[index] + ".csv",
            dataType: "text",
            success: function(data) {
                processData(data, options[index], type)
            }
        });
    })(i);
}
setTimeout(function() {
    getAveragePercentages(lines);
}, 500)

Solution

  • You can use the JavaScript promise functionality.

    Make AJAX request in the promise. Create an array which will contains all these promise.

    Promise.all will be executed after all promise get resolved.

    var promiseArr = [];
    for (var i = 0; i < options.length; i++) {
        var promise = new Promise(function(resolve, reject) {
            (function(index) {
                $.ajax({
                    type: "GET",
                    url: options[index] + ".csv",
                    dataType: "text",
                    success: function(data) {
                        processData(data, options[index], type); resolve('outputIfany')
                    }
                });
            })(i);
        });
        promiseArr.push(promise);
    }
    Promise.all(promiseArr).then(function(values) {
        getAveragePercentages(lines);
    });