Note: The goal of this article is to get you to the core idea and basic usage of Promise as quickly as possible. For more details on how to use Promise in a comprehensive way, please read the official API
In addition: This article assumes that you have a basic knowledge of asynchronous programming, such as callbacks, chainlink calls, and a basic vocabulary such as page, user, promise, then, resovle, reject, pay, fix, order, and so on. If you are very unfamiliar with these words, then you need to take some time to replenish your English first, otherwise you will still find this article difficult to understand. (Refer to the information asymmetry principle I explained in the presentation training video.)
What is asynchronous operation?
Asynchronous operations are those that can be performed simultaneously with the current program.For example:
$("#page").scrolltop(0 ,1000); $("#nav-float").hide (1000); $("#nav-float").hide (1000); // Hide the hover navigation bar for 1 second
If you have any experience with asynchronous programming, you should know that these two methods work together.
The order in which they are written does not affect the order in which they are executed
// Asynchronous operations do not interrupt the execution of the current program. Ajax ("/getUsers",function(data) {// Resumelist will be called on success}) // Resumelist will start immediately, Whether or not getUsers closes the ajax("/ Resumelist ", function(data) {}) // It is not clear from the order of writing which Ajax returns the result first and executes the callback function.
We can give a simple definition of asynchronous operations
When an operation begins to execute, the main program does not have to wait for its completion and can continue to execute. At this point, the operation can be the same as the main program and is called asynchronous operation. Usually, when the operation is complete, we execute a pre-defined callback function to do the rest of the processing. When (concurrently). This kind of operation we do
Our common asynchronous operations are:
What are the problems with asynchrony?
For example, we have two animations that need to be executed in sequence, so the first one ends and the second one starts
This can be a bit of a hassle, but the traditional solution is to call back:
animateA(function( ){
animateB( );
})
This is obviously a bad idea, because if you have a lot of asynchronous operations that need to be executed sequentially, you can get what’s called callback hell.
ajaxA(function( ){
ajaxB(function( ){
ajaxC(function( ){
ajaxD(function( ){
......
});
});
});
})
This kind of code is annoying to write and read. Let’s take a look at what Promise looks like (pseudocode)
new Promise(ajaxA)
.then(ajaxB)
.then(ajaxC)
.then(ajaxD);
The use and rationale of Promise
To master Promise, you must first understand how it solves problems
Post the actual Promise code so you can get a feel for it:
newPromise(resolve=>{ ajax("/pay/post", data=>resolve() ); }). Then (resolve = > {ajax ("/order/fix, "data = > {/ / processing data})})
The above code uses the ES6 arrow function, which greatly simplifies code writing, but is extremely unfriendly to beginner programmers
Reading this code is almost like reading Diamond Sutra. Let’s restore the code to what it looks like in ES5
new Promise(function(resolve){
ajax("/pay/post",function(data){
resolve();
})
}).then(function(){
ajax("/order/fix",function(data){
})
})
Next, we’ll follow the Feynman technique step by step to learn how Promise solves a problem
Question 1
As an asynchronous function, especially a network request like Ajax, where even I can’t determine the execution time of the function, how does Promise know when the first function ends? And then start executing the next one?
Promise is not that magical. It doesn’t know when our function ends. Did you notice line 3 in the code above
At the end of the Ajax request callback execution, we call a resolve() function, which is crucial.
This is essentially telling the Promise that the current function is finished and you can start executing the next one. Then the Promise will execute the function inside the Then.
Question 2
.
So if I don’t call this method, the Promise won’t know if the function ends, and the function inside the then won’t execute, meaning my second request will never be sent?
Bingo!! Congratulations you have learned logical reasoning + rush answer.
Question 3
But this
resolve
Where did the function come from? Do I have to define it myself? From the code it looks like it’s a parameter, and who passed that into the function?
You need to understand the basic structure of Promise
New Promise(function 1).then(function 2);
We passed both functions 1 and 2 as arguments to a Promise object, so functions 1 and 2 will be controlled by the Promise object. In short, functions 1 and 2 will be executed by the Promise object. So when function 1 executes, of course, the arguments are passed in by the Promise object.
New Promise(function(resolve){//resolve is the argument passed by the Promise object when the function is called).then(function 2);
Question 4
.
Why would the Promise object put this on the first task
resolve
What’s the purpose of this function?
What do you say?
Asshole, don’t you have to ask?
What a pig’s brain! Didn’t you just say that? The Promise object has no way of knowing when our asynchronous function ends. What would you do if you went to the station to meet someone and you didn’t know when they would get off?
Give him my number. Call me when you get there
Yes, Promise solved the problem along the same lines. It passes in the resolve function, which acts like a walkie-talkie to notify the Promise object when our asynchronous task is about to end. This means calling the resolve method
New Promise(function(resolve){ajax("/pay/post",function(data){// When the request ends, call the resolve method to tell the Promise object that the task has resolved (); })}).then(function 2);}).then(function 2);
So the resolve function, which must be called at the end of an asynchronous task (such as an Ajax callback method), tells the Promise object that this task is over and that it’s time to start the next one.
Absolutely right
Question 5
.
So Promise is no more than that; it doesn’t revolutionize functionality, because you can do the same thing with traditional callback nesting. To put it bluntly, it is an improvement in the way of coding??
That’s basically true, but the advance in coding and thinking about asynchronous programming that Promise brings is huge.
Question 6
.
If I have three asynchronous tasks, ajaxA, ajaxB, and ajaxC, and I want to execute them in the order of A, B, and C, can I write it like this?
no
Depend! I haven’t told you yet!
That you said
What if I write it this way?
new Promise(function(resolve){ ajax("/AAA", function(){ resolve(); })}).then(function(resolve){ajax("/BBB", function(){resolve(); / / notification Promise the mission ends})}). Then, the function () {ajax ("/CCC ", function () {/ /... })})
This is not true. Promise in Chinese means “Promise”, which means that every Pormise object represents a Promise
And each commitment can only guarantee the order of a task, that is to say
new Promise(A).then(B); So this is just saying that the order of A and B is guaranteed.
Once A has finished executing and B has started, the Promise has been fulfilled and the Promise object is invalidated
What if we have C? We would then have to recreate a new Promise object in function B to complete the next Promise, written like this:
New Promise(function 1(resolve){ajaxA(" XXXX ", function(){resolve(); })}).then(function 2(){// After function 2 starts, the Promise object that was first created completes its mission and can no longer work. Return new Promise(function(resolve){ajaxB(" XXXX ", function(){resolve(); })})}).then(function 3(){// The new Promise object is already in charge of executing function 3, even though we are using a chain call. AjaxD (" XXX ", function(){})});
Question 7
.
Okay, so what other powerful things can Promise do?
Yes, for example, if I have three asynchronous tasks A, B, and C, ABC will start executing simultaneously
When all three tasks A,B, and C are completed, and task D is implemented in the traditional way, the Promise is very simple, like this:
Promise.all([new Promise(A), new Promise(B), new Promise(C)])
.then(function(){
D();
});
Question 8
.
So if I wanted to
A
.B
.C
If you complete any of these tasks, you start task D. What do you do?
Promise.race([new Promise(A), new Promise(B), new Promise(C)])
.then(function(){
D();
});