For example, I have an A.func1() that is asynchronous and it can return an object x1. I also have a B.func2() that is also asynchronous and needs to be executed based on x1, and then B.func2 returns a final value. value t, and some prompt displays will be performed based on this final value t. How should I write this?
The code I wrote myself is like this
A.func1().
then(function(x1) {
B.func2(x1).
then(function(t) {
//do something
})
})
But it feels like the effect is the same whether you use then or not...it still turns back into a pyramid
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