AngularJS:如何扁平化这一承诺链? [英] AngularJS : How to flatten this Promise chain?

查看:149
本文介绍了AngularJS:如何扁平化这一承诺链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

someService.fnReturnsPromise()
    .then(function () {
        return someService.fnReturnsAnotherPromise(someArg);
    })
    .then(function (resultsOfSecondFn) {
        // do stuff with results
    });

我觉得好像这应该工作;然而, resultsOfSecondFn 是不实际的结果,它的承诺本身,我回来了。为了使它工作的方式我想,我必须这样做:

I feel as if this should work; however, resultsOfSecondFn isn't actually the results, it's the promise itself that I returned. To make it work the way I want, I have to do this:

someService.fnReturnsPromise()
    .then(function () {
        return someService.fnReturnsAnotherPromise(someArg);
    })
    .then(function (promiseReturn) {
        promiseReturn.then(function (results) {
            // do stuff with results
        });
    });

这是伪code为 fnReturnsAnotherPromise

someService.fnReturnsAnotherPromise = function (arg1) {
    return anotherService.anotherFnThatReturnsPromise(arg1);
};

因此​​,其实,这只是一个额外的一层,而是一个应许被退回两种方式。为code anotherFnThatReturnsPromise $ q.defer的简单模式()回dfd.promise 一些解析()秒。

推荐答案

像角的承诺是承诺/ A +标准,是保证递归吸收承诺。这正是为了避免嵌套和简化事情像你的情况,是承诺的地步。

Promises like Angular's are Promises/A+ compliant and are guaranteed to recursively assimilate promises. This is exactly to avoid nesting and simplify things like your case and is the point of promises.

所以,即使你有一个返回,返回一个承诺,承诺和誓言,你可以在一个单一的。然后通话解开它。例如:

So even if you have a promise that returns and a promise that returns a promise you can unwrap it in a single .then call. For example:

var p  = $q.when(1); // Promise<Int>
var p2 = $q.when().then(function(){ return p;  }); // Promise<Promise<Int>>
var p3 = $q.when().then(function(){ return p2; }); // Promise<Promise<Promise<Int>>>>
p3.then(function(result) {
    console.log(result); // Logs 1, and Int and not p2's type
});

或者在你的例子:

Or in your example:

someService.fnReturnsPromise()
.then(function() {
    return someService.fnReturnsAnotherPromise(someArg);
})
.then(function(resultsOfSecondFn) {
    // do work with results, it is already unwrapped
});

请参阅this用另一种语言比较的诺言没有展开的观点。

See this comparison with another language for perspective on promises not unwrapping.

这篇关于AngularJS:如何扁平化这一承诺链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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