比如我有一个A.func1()是异步的,它能返回一个对象x1,我还有一个B.func2()也是异步的,需要根据x1来执行,然后B.func2返回一个最终值值t,根据这个最终值t就进行一些提示性显示。请问这个要怎么写呢?
我自己写的代码是这样的
A.func1().
then(function(x1) {
B.func2(x1).
then(function(t) {
//do something
})
})
但是感觉这样用不用then就一个效果啦……还是变回金字塔了
In response to the supplementary comment in the comments about "saving state during continuous calling of promises", I would like to elaborate on several strategies
The best strategy: De-statement
That is, adjust your logic so that the calling process of A.func1, B.func2, and the anonymous function (let’s call it func3) does not contain state, that is, let func3 only rely on the output of func2 and not the output of func1. ; Or let func2 not depend on func1, use something like
Promise.all
to get the results of func1 and func2 at the same time and throw them to func3Central strategy: "global" variables maintain status
Advantages: state can be extended state.x2 .x3...
The bind method ofProblem: If a long call chain has complex states, it is easy to contaminate bugs, and the maintainability of the code will be seriously reduced
bluebird
can bind thisArg and can be used to retain the state. The principle is the sameChoice: Temporary additional delivery
Advantages: Without state, if the call chain is long, this extra state is controlled between two steps, maintaining better maintainability and less prone to bugs
Disadvantages: If each step of the long call chain has a state, it will become extremely verbose
Of course, the inner then here can also be encapsulated and optimized by yourself
Last solution: Closures maintain state
This is actually the original way of writing the question. I think the main problem is that the question has been downgraded back to the original "callback hell" or the embarrassment of the callback pyramid
The advantage is...it works
The object directly in
then
里面返回一个Promise
, as follows:In response to the problem mentioned in your comment, if you do not use a third-party
Promise
library, you can use it as follows:Using third-party
Promise
libraries can simplify this process.Promise will return a promise object, so that it can use elegant chain calls.
If the return value of the function in then is a direct quantity, it will be used as the parameter of then in the next chain call.
If the return value has the interface of promise, the result of the resolve of the promise is returned.
Using q as an example