What is promise?

Time:2021-10-21

The main purpose of this article is to introduce the usage of promise in the front end. Although there are many explanatory documents, it is not friendly for novices. Here I’ll explain it in the simplest vernacular with examples. I won’t talk much nonsense. Let’s start today’s introduction.

Function: solve the problem of callback hell, and change the code mode of function nesting to horizontal.

  When a callback function is nested with a callback function, a nested structure will appear. When nested more, callback hell will appear.

  In order to understand promise more clearly, we need to observe a piece of game code first.

Therefore, the above functions are nestedgameThe code can be modified to:

There are four functions in the code segment. F1, F2, F3 and F4 are all functions, and the latter function is used as the parameter of the previous function, and then nested calls are made. Finally, from the syntax of the call, the code is very complex. We call the callback function as callback hell.

  The purpose of pomise is to change the nested call mode to horizontal. In other words, from the result of the call, there is no difference in essence. Poise only changes the writing rules of grammar. This is the basic usage of pomise.

  Promise's syntax rules are as follows:



  Here, the promise object can pass the callback function previously passed through formal parameters with the then method. In fact, www.diuxie.compose mainly deals with asynchronous operations, such as common Ajax requests. Each of our asynchronous events, when executed, will have three states: in execution, success and failure. This explains why the then method has two parameters. Parameter 1 represents the callback function executed upon success, and parameter 2 represents the execution state upon failure.

  



  The function implemented in this way is exactly the same as that of the above code, but it solves the trouble of function nested call.

  Conclusion: the role of pomise is to change the nested call mode to horizontal, which is used to handle asynchronous operations.