AngularJS $q. Deferred queue

Don’t use a queue and that boolean flag, just have one variable storing a promise representing all uploads. Also, your upload function should not take a Deferred object to resolve as an argument, but simply return a new promise.

Then the addAnUpload becomes as simple as

var allUploads = $q.when(); // init with resolved promise

function AddAnUpload(file) {
    allUploads = allUploads.then(function() {
        return upload(file);
    });
}

With the closure, you don’t need that queue to store the waiting uploads any more. If you want allUploads to fulfill always, even if one upload fails, you need to return an always-fulfilling promise from the then-callback:

        return upload(file).then(null, function(err) {
            console.log(err, "does not matter");
        }); // fulfills with undefined in error case

Leave a Comment