Tân
Tân

Reputation: 1

Using $.when().done() to wait for downloading complete

I wanna download multiple json files and compress data to a cookie. First of all, I save them to an array, then I use JSON.stringify() to compress it.

I've tried:

var files = [];
$.when(
    ['file1', 'file2', 'file3'].forEach(function (f) {
        $.getJSON('/scripts/json/' + f + '.json', function (data) {
            files.push(data);
            console.log(files) // checking ok
        })
    })
).done(
    console.log(files); // Oops... this line will be excuted before $.when()
    $.cookie('files', JSON.stringify(files)) // compress before saving
)

As you can see, jquery compiler won't know exactly when the files are downloaded complete.

So, my question is: How to wait them?

Upvotes: 1

Views: 64

Answers (1)

adeneo
adeneo

Reputation: 318332

You're iterating inside $.when, but you're not passing the Deferreds back, so $.when only receives the returned result from Array.forEach, which is always undefined, so basically what you're doing is

$.when(undefined).done();

You can to pass an array to $.when if you use apply, and mapping, using map() instead of forEach() would return an array of the Deferreds

$.when.apply($,
    ['file1', 'file2', 'file3'].map(function (f) {
        return $.getJSON('/scripts/json/' + f + '.json');
    })
).then(function() {
    var files = [].slice.call(arguments).map(function(x) { return x[0]; });
    $.cookie('files', JSON.stringify(files)) // compress before saving
}, function(err) {
     // failed
});

Upvotes: 1

Related Questions