7

I'm returning a promise from a function like this:

resultPromise = dgps.utils.save(opportunity, '/api/Opportunity/Save', opportunity.dirtyFlag).then(function () {

                self.checklist.saveChecklist(opportunity).then(function () {

                    self.competitor.save(opportunity.selectedCompetitor()).then(function ... etc.
return resultPromise;

Let's say the above function is called save.

In the calling function I want to do wait for the entire chain to complete and then do something. My code there looks like this:

var savePromise = self.save();
savePromise.then(function() {
    console.log('aftersave');
});

The result is that 'aftersave' is send to the console while the chain of promises is still running.

How can I do something after the whole chain is complete?

RolandG
  • 1,269
  • 4
  • 14
  • 21

1 Answers1

8

Instead of nesting the promises, chain them.

resultPromise = dgps.utils.save(opportunity, '/api/Opportunity/Save', opportunity.dirtyFlag).then(function () {

                    return self.checklist.saveChecklist(opportunity);
                }).then(function () {

                    return self.competitor.save(opportunity.selectedCompetitor());
                }).then(function () {
                    // etc
                });

// return a promise which completes when the entire chain completes
return resultPromise;
Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • 2
    what if there's a conditional in there? Wouldn't you need the deferred object? – FlavorScape Jan 28 '15 at 00:13
  • This is not the answer to question asked. The question was how to wait for chain to end. Simply adding more elements to the chain is not a solution and often won't work properly. – MeanEYE Jun 08 '16 at 13:57
  • @MeanEYE You wait t for the chain to end by doing a `then` on the chain. This solves the problem (though as you noted, it doesn't answer the literal question, but the question was really about a problem). – Raymond Chen Jun 08 '16 at 14:51