Author: Ke Ke (Hujiang front end development engineer)
This article is an original article. You are welcome to point out some mistakes. Please indicate the source of the reprint.
The emergence of a new thing must have its historical reasons. In order to write asynchronous code in a synchronous way, people have broken their heart in JS. From deferred to promise to generator, then to async and await, the emergence of various tools is like the evolutionary history of human civilization, from scratch to perfection.
Among them, promise is one of the most important tools, and it is also the cornerstone of the evolution of different tools. Today, let’s understand why we need promise and what problems it has solved for us.
What do we need?
1. Back to hell
We should all have encountered such code:
It’s good to have fewer layers of callback nested functions. If you have more, a lot of indentation will slowly move your code to the right side of the screen. If you write dozens of callbacks, your code may not fit on the width of one screen. This makes our code hard to maintain, like a lump of *. To be sure, we can treat the code equally in other ways, such as:
Although this is good-looking, but: 1. Cut off the hierarchical concatenation of our code structure, but use the unstructured pointing concatenation, skipping function references, it is likely to confuse us. 2. Spend more time to organize the code
What we want is to be able to string together and spend less time. Promise just solved such a pain point.
var promise = new Promise(...); promise.then(...) .then(...) .then(...) .then(...) .catch(...)
yes! What we really want is such a “grammar sugar”.
2. Don’t let return and throw in callback become devices
Think about writing a return XXX in the success callback of $. Ajax (). It’s useless. Who is the return to? It felt like an empty punch. In addition, if you throw an error in an asynchronous callback, you want to take it out. For example, you want to do this:
congratulations! If not, error is thrown into the global environment, boom! Then the main thread hangs.
What is the promise solution?
First of all, the literal meaning of promise is somewhat abstract. To be more concrete, we can regard promise as the manager and executor of some kind of “contract“.
Yes, we can think of “he” as a person and give him a short name, which is “Mr. P”. Now, let’s take a look at how Mr. P helps us solve the problem (since the solution is provided by Mr. P, we need to follow his routine).
1. Make a contract
First of all, we need to write down a “contract” according to the appearance of a certain template. What Mr. P is told in the contract is what may happen in the future. Mr. P will deal with and give feedback on the matters we have agreed with him. Promise only deals with two basic situations in the future: success and failure.
In the above code, first we call (New) a “Mr. P”, and then tell “he” the specific contract content in the callback function. The contract stipulates: in the setTimeout asynchronous operation, if the number of seconds obtained is greater than 30s, the contract will become effective and complete; otherwise, the contract will become invalid and complete. “Mr. P” nodded and said, “OK, no problem.”.
Note: once the resolve or reject operation is completed, the status of the contract is dead, and there is no way to change it.
2. Operation after completion of the contract
After the last step, Mr. P will only tell us the result of the contract: success or failure. So what to do after success? What to do after failure? We haven’t told Mr. P yet. Let’s wave our little hand (quoting promise variable) to call Mr. P and continue to ask:
Then gives a solution to the specific needs of success or failure, which needs to pass two processing functions
If only the onrejected function is passed in then, it is equivalent to catch.
Seeing this, we find that promise helps us solve the problem of error capture to a certain extent. In the above example, the errors we make in the then chain can be caught in the end by catch (if you write catch on the last side).
What should the functions in then write?
Each promise will provide you with a then () function. When our code runs inside the then() function, it looks like this:
What can we do inside this function?
That is to say, I can write as follows:
In the above example, we can happily use return and throw in then, and smoothly pass the value to the next layer then or catch for processing. Here, promise has actually solved the problem we said before: “return and throw cannot be used effectively in asynchronous callbacks.”
Seeing this, you must have clearly realized what promise is and helped us solve some problems, right? Of course, the promise API also provides many methods, such as race, all, reject, resolve. The main purpose of this article is to explain the reason of promise and what problems “he” has solved. As for other methods on API, I believe it will be easy to master on the basis of understanding promise.
Promise is just a brilliant point on the road of “asynchronous” to “synchronous”, and “he” still has some defects and shortcomings, which is not our final solution. Next time, we will learn a new tool: generator!
We have a problem with problems
Ikcamp’s original new book, the effective development of mobile web front end, has been on sale in Amazon, Jingdong and Dangdang.