1

I have a simple jQuery script which parses some json files:

var jsonData = {};

$.when(
    $.getJSON('data/file1.json', function(data) {
        jsonData['file1'] = data;
    }),
    $.getJSON('data/file2.json', function(data) {
        jsonData['file2'] = data;
    })
).then(function() { 
    // do stuff
});

What I would like to do is make this more extensible by being able to loop through a list of files.

I have tried this:

var jsonData = {};
var files = ['file1.json', 'file2.json'];

$.when(
    $.each(files, function( index, value ) {
        $.getJSON('data/' + value, function(data) {
            jsonData[value] = data;
        })
    })
).then(function() { 
    // do stuff
});

But then I seem to loose the asynchronous nature of the call.

1 Answer 1

2

Try this:

var jsonData = {};
var files = ['file1.json', 'file2.json'];

// make array of promises

gets=$.map(
    files,
    function(f){ 
        return $.getJSON('data/'+f, function(data) {
            jsonData[f] = data;
        });
    }
);

$.when
    .apply(null,gets)
    .then(function() { 
        // do stuff
    }).fail(function() {
        // handle error
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.