gpt4 book ai didi

javascript - Angular : How to flatten this Promise chain?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:46:14 24 4
gpt4 key购买 nike

我有以下代码:

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

我觉得这应该行得通;但是,resultsOfSecondFn 实际上并不是结果,它是我返回的 promise 本身。为了让它按照我想要的方式工作,我必须这样做:

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

实际上,它只是一个额外的层,但无论哪种方式都会返回一个 promise 。 anotherFnThatReturnsPromise 的代码是 $q.defer() 的简单范例,return dfd.promise 带有一些 resolve()s.

最佳答案

像 Angular 这样的 Promise 是 Promises/A+ 兼容的,并且保证递归地吸收 promises。这正是为了避免嵌套和简化您的情况,并且是 promise 的重点。

因此,即使您有一个返回的 promise 和一个返回 promise 的 promise ,您也可以在单个 .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
});

或者在你的例子中:

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

参见 this comparison with another language对未展开的 promise 的看法。

关于javascript - Angular : How to flatten this Promise chain?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25512015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com