Author: Du Keke (Hujiang Front-end Development Engineer)

This article is an original article, welcome to point out any inappropriate. Please indicate the source for reprinting.


There must be a historical reason for the emergence of a new thing. In order to write asynchronous code in a synchronous way, people worry a lot about JS. From Deferred to Promise to Generator to Async and Await, the emergence of tools is like the evolution of human civilization, from nothing, from the humble to the perfect.


Promise is one of the most important tools, and it is also the cornerstone of the evolution of different tools. Today, let’s take a look at why we need promises and what they solve for us.


What do we need?


1. Callback hell


We’ve all come across code like this:




Fewer layers of callback nested functions would be better, if more, and a lot of indentation would slowly move your code to the right of the screen. If you write dozens of callbacks, your code might not fit on the width of a screen. This would make our code unmaintainable, like a mess of *. There are other ways in which code can be pulled horizontally, such as:





This is nice, but: 1. It cuts off the hierarchical concatenation of our code structure, and instead uses unstructured pointing concatenation, hopping function references that probably confuse us. 2. It takes more time to clean up the code


What we want is to be able to string things together and take less time. Promise addresses just such a pain point.


var promise = new Promise(...) ; promise.then(...) .then(...) .then(...) .then(...) .catch(...)


Right! What we really need is such “grammar sugar”.


2. Don’t let the return and throw in the callback become useless


$.ajax() {return XXX = $.ajax(); It feels like a punch in the air. Alternatively, if you throw an error in an asynchronous callback and want to catch it, for example:





Congratulations to you! Error is thrown into the global environment. BOOM! And then the main thread dies.


What is the Promise solution?


First, look at the literal meaning of Promise. The translation of “Promise” is somewhat abstract. Concretely, then, we can think of promises as the manager and enforcer of a kind of “contract.”


Yes, we can think of him as a person and give him a short name: “Mr. P”. Here’s a look at how “Mr. P” helped us solve our problems (since “Mr. P” provided the solutions, we need to follow “him”).


1. Make a contract


First of all, we need to write a “contract” in accordance with a template. The “contract” tells “Mr. P” what may happen in the future. “Mr. P” will deal with and give feedback on the matters agreed between us and “him”. Promise makes only two basic case responses to future events: “success” and “failure.”



In the above code, we first call a “Mr. P”, and then tell “him” the specific contract content in the callback function. The contract stipulates that: in the setTimeout asynchronous operation, if the number of seconds obtained is more than 30 seconds, the contract will be effective and complete. Otherwise, the contract is void and complete. “Mr. P” nodded and said, “Yes, no problem.”


Note: Once resolve or Reject is complete, the contract status is resolved and cannot be changed.


2. Operations after the contract is completed


After the previous step, “Mr. P” will only tell us the outcome of the contract completion: success or failure. So what do you do when you succeed? What to do after failure? We haven’t told “Mr. P” yet, so let’s wave “Mr. P” over (citing the promise variable) and continue:





Then gives you a solution to the specific requirements for success or failure, which requires passing two handlers



If only the onRejected function is passed in then, it is equivalent to a catch.


As we look at this, we see that promises help solve the problem of error capture to some extent. In the example above, any errors we make in the then chain will eventually be caught by catch (if you write catch at the end).


What do I write in the function then?


Each promise gives you a then() function. When our code runs inside the then() function, it looks like this:





What can we do inside this function?





So I could write:







As we saw in the example above, we can happily use return and throw in THEN and pass the value to the next layer of THEN or catch for processing. Promise has solved the problem we discussed earlier: “Return and throw cannot be used effectively in asynchronous callbacks.”


conclusion


See here, presumably you should have a clear understanding of what Promise is, and help us solve what problem? Of course, the Promise API also provides many methods, such as Race, All, Reject, and Resolve. The main purpose of this article is to explain why promises come into being and what problems “they” solve. As for the other methods on the API, I believe that based on understanding promises, it will be easy to grasp.


Promise is just a bright spot on the asynchronous “to” synchronous road, and it has some flaws and limitations, but it’s not the final solution. Next time, we’ll learn about a new tool together: Generator!


References:

【 例 句 】We have a problem with promises

JavaScript Promise Mini-Book (Chinese version)

ES6 JavaScript Promise perceptual cognition

Promise – JavaScript | MDN