AngularJS:如何展平这个 Promise 链? [英] AngularJS : How to flatten this Promise chain?

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

问题描述

我有以下代码:

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

这是fnReturnsAnotherPromise的伪代码:

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

所以真的,这只是一个额外的层,但无论哪种方式都会返回一个承诺.anotherFnThatReturnsPromise 的代码是 $q.defer() 的简单范例,return dfd.promise 和一些 resolve()s.

So really, it's just one extra layer, but a promise is getting returned either way. The code for anotherFnThatReturnsPromise is the simple paradigm of $q.defer(), return dfd.promise with some resolve()s.

推荐答案

像 Angular 这样的 Promise 是 Promises/A+ 兼容的,并且保证递归地同化 Promise.这正是为了避免嵌套和简化诸如您的案例之类的事情,这也是 Promise 的重点.

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.

因此,即使您有一个返回的承诺和一个返回承诺的承诺,您也可以在单个 .then 调用中解开它.例如:

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

或者在你的例子中:

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

参见这个与另一个的比较语言,用于看待未展开的承诺.

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

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

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