javascript 等到 promise 和嵌套 then 完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14173228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:54:52  来源:igfitidea点击:

Wait until promise and nested thens are complete

javascriptjquery-deferredpromise

提问by RolandG

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.

结果是在承诺链仍在运行时将“aftersave”发送到控制台。

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

整个链条完成后我该怎么做?

回答by Raymond Chen

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;