jacob
jacob

Reputation: 541

async foreach in jquery

I am trying to display some charts using c3js. And I have come across the problem of having a need for "pausing" a foreach loop with a async operation in the loop. I can hack it by a adding an empty alert which allows the "work" to be completed (see the alert in code below). How do I unhack this and make it work? The showData function is called when pressing a button.

selectedFiles = [];    
function showData(){
        displayChart(selectedFiles,function(cols){
            alert("");//fixme
            //display chart
            chart = c3.generate({
                bindto: '#chart',
                data: {
                  columns: cols,
                type:'bar'},
                bar: {
                        width: {
                            ratio: 0.5 
                        }
                    }
            });     
        });
    }

    function displayChart(files,completionHandler)
    {
        var columns = [];
        $.each(files, function( index,value) {
            //create array with file name, and averageDuration
            var fileName = value + ".json";
            var averageDuration;
            $.getJSON(fileName, function(json) {
                averageDuration = json.averageDuration;
                var col = [value,averageDuration]; 
                columns.push(col);
            });         
        });
        completionHandler(columns);
    } 

Upvotes: 0

Views: 427

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

since ajax is async, you can't use it like that

function displayChart(files, completionHandler) {
    var src = $.map(files, function (value) {
        var fileName = value + ".json";
        return $.getJSON(fileName);
    });
    $.when.apply($, src).done(function (data) {
        var columns;
        if (files.length > 1) {
            columns = $.map(arguments, function (array, idx) {
                return [[files[idx], array[0].averageDuration]]
            });
        } else {
            columns = [
                [files[0], data.averageDuration]
            ]
        }
        completionHandler(columns);
    })
}

Demo: Fiddle

Upvotes: 2

Related Questions