AngularJS:如何压扁这个Promise链?

use*_*125 4 javascript chaining promise angularjs angular-promise

我有以下代码:

someService.fnReturnsPromise()
    .then(function () {
        return someService.fnReturnsAnotherPromise(someArg);
    })
    .then(function (resultsOfSecondFn) {
        // do stuff with results
    });
Run Code Online (Sandbox Code Playgroud)

我觉得这应该有效; 然而,resultsOfSecondFn实际上并不是结果,而是我回来的承诺本身.为了让它按照我想要的方式工作,我必须这样做:

someService.fnReturnsPromise()
    .then(function () {
        return someService.fnReturnsAnotherPromise(someArg);
    })
    .then(function (promiseReturn) {
        promiseReturn.then(function (results) {
            // do stuff with results
        });
    });
Run Code Online (Sandbox Code Playgroud)

这是伪代码fnReturnsAnotherPromise:

someService.fnReturnsAnotherPromise = function (arg1) {
    return anotherService.anotherFnThatReturnsPromise(arg1);
};
Run Code Online (Sandbox Code Playgroud)

所以真的,它只是一个额外的层,但承诺是以任何一种方式返回.代码anotherFnThatReturnsPromise是一些简单的范例$q.defer(),return dfd.promise有些resolve()是s.

Ben*_*aum 6

像Angular这样的承诺是Promises/A +兼容,并保证以递归方式同化承诺.这正是为了避免嵌套并简化像你的情况这样的事情,这是承诺的重点.

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

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
});
Run Code Online (Sandbox Code Playgroud)

或者在你的例子中:

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

请参阅与另一种语言的比较,以了解未展开承诺的观点.