AngularJS : How to flatten this Promise chain?

余生长醉 提交于 2019-12-04 10:13:05
Benjamin Gruenbaum

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

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

you could try it this way:

someService.fnReturnsPromise().then(function () {
    someService.fnReturnsAnotherPromise(someArg).then(function (results) {
        console.log(results);
    });
});

Hope it helps!

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