等到承诺和嵌套版本完成 [英] Wait until promise and nested thens are complete

查看:70
本文介绍了等到承诺和嵌套版本完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从这样的函数返回一个承诺:

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;

假设上面的函数叫做save​​。

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');
});

结果是'aftersave'被发送到控制台,而Promises链仍然在运行。

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

在整个链是comp之后我该怎么办? lete?

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

推荐答案

不是嵌套承诺,而是将它们链接起来。

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;

这篇关于等到承诺和嵌套版本完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆