Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method once all deferred completes?

I have this class:

(function(){
"use strict";

var FileRead = function() {
    this.init();
};


p.read = function(file) {

    var fileReader = new FileReader();
    var deferred = $.Deferred();

    fileReader.onload = function(event) {
        deferred.resolve(event.target.result);
    };

    fileReader.onerror = function() {
        deferred.reject(this);
    };

    fileReader.readAsDataURL(file);

    return deferred.promise();

};

lx.FileRead = FileRead;
}(window));

The class is called in a loop:

var self = this;
    $.each(files, function(index, file){
        self.fileRead.read(file).done(function(fileB64){self.fileShow(file, fileB64, fileTemplate);});

    });

My question is, is there a way to call a method once the loop has completed and self.fileRead has returned it's deferred for everything in the loop?

I want it to call the method even if one or more of the deferred fails.

like image 906
panthro Avatar asked Oct 21 '22 06:10

panthro


1 Answers

$.when lets you wrap up multiple promises into one. Other promise libraries have something similar. Build up an array of promises returned by fileRead.read and then pass that array to $.when and hook up then/done/fail/always methods to the promise returned by .when

    // use map instead of each and put that inside a $.when call
    $.when.apply(null, $.map(files, function(index, file){
        // return the resulting promise
        return self.fileRead.read(file).done(function(fileB64){self.fileShow(file, fileB64, fileTemplate);});

    }).done(function() {  

      //now everything is done 
    })
like image 93
Robert Levy Avatar answered Oct 23 '22 02:10

Robert Levy