The main purpose of this article is to show you how Promise can be used in the front end, and while there’s a lot of documentation, it’s not very friendly to beginners. Here I will give you the most simple vernacular explanation, and with examples, without further ado began today’s introduction.
Action: Solves the callback hell problem by changing the way functions are nested in code to be flat. When a callback function is nested within a callback function, a nested structure occurs, and when too many are nested, callback hell occurs. To understand Promise more clearly, we need to look at a piece of game code.
So the game code for the above nested function call can be modified as follows:
The code snippet has four functions,f1,f2,f3, and f4, with the latter function as an argument to the previous function, which is then called nested. In the end, the code is so complex in terms of the syntax of the call that we call it callback hell. The function of Pomise is to change the nested invocation mode to a flat one. That is to say, from the perspective of the results of invocation, there is no difference in essence in the end, and PORMISE only changes the writing rules of grammar. This is the basic way to use Pomise. The syntax for Promise is as follows: Here a Promise object can pass a callback function that was previously passed through a parameter using a then method. In fact, www.diuxie.compromise mainly handles asynchronous operations, such as common Ajax requests. Each of our asynchronous events, at the time of execution, has three states: execution, success, and failure. This explains why a then method takes two arguments, argument 1 representing the callback function executed on success and argument 2 representing the execution state on failure. This does exactly the same thing as the code above, but eliminates the hassle of nested function calls. Conclusion: The function of Pomise is to change the nested invocation mode to a horizontal one, which is used to handle asynchronous operations.