Wait until promise and nested thens are complete

别说谁变了你拦得住时间么 提交于 2019-12-12 10:38:34

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/14173228/wait-until-promise-and-nested-thens-are-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!