Nate
Nate

Reputation: 7856

AngularJS create deferred function

I'm new to angularJS and still have some difficulties with promises... I have the following function:

   removeMultipleAttachments: function(docid, rev, attachmentIDs) {

        var p = $q.when();
        angular.forEach(attachments, function(file, index) {
            return p.then(function (formerRes) {
                return pouch.removeAttachment(docid, attachmentIDs[index], rev);
            }).then(function(res) {
                rev = res.rev;
                $rootScope.$apply();
            });
        })
   }

and would like to be able to call it and use a .then() with the responses when it finishes such as:

removeMultipleAttachments(mydocID, myRev, myAttachments).then(function(responses){ ---is called only when done ---  })

Upvotes: 2

Views: 97

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

Doing $q.when() creates an empty resolved promise

What you're trying to do is chain completions. You're almost there, the problem is that you're returning in the forEach instead of chaining.

Try:

removeMultipleAttachments: function(docid, rev, attachmentIDs) {

        var p = $q.when();
        var retvals = [];
        angular.forEach(attachments, function(file, index) {
            p = p.then(function (formerRes) { // NOTE THE ASSIGNMENT HERE
                return pouch.removeAttachment(docid, attachmentIDs[index], rev);
            }).then(function(res) {
                retvals.push(res);
                rev = res.rev;
                $rootScope.$apply(); // You really don't need the apply here
            });
        })
        return p.then(function(){ return retvals; }); // AND THE RETURN HERE
   }

Note this will execute sequentially, one promise at a time. If you want to execute all the requests at once, you can use $q.all:

removeMultipleAttachments: function(docid, rev, attachmentIDs) {
    var p = $q.when();
    return $q.all(attachments.map(function(file,index){ 
        // not sure what to do with the res.rev = rev part
        return pouch.removeAttachment(docid,attachmentIDs[index], rev);
    });
}

Upvotes: 1

Related Questions