This article has participated in the call for good writing activities, click to view: back end, big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!


Help you to clarify the process of learning a knowledge point

Note: This article is intended to get you through the core ideas and basic uses of Promise as quickly as possible. For more details on how Promise is used, read the official API

In addition: This article assumes that you have basic knowledge of asynchronous programming, such as callbacks and chained calls, as well as a basic vocabulary of words such as Page, User, promise, then, Resovle, Reject, pay, fix, Order, etc. If these words are very new to you, then you need to take some time to refresh your English first, otherwise you will still find this article difficult to understand.


What is an asynchronous operation?

Asynchronous operations are operations that can be performed simultaneously with the current program.For example:

$("#page").scrolltop(0 ,1000);    // Take 1 second to scroll to the top of the page

$("#nav-float").hide (1000);    // Use 1 second to hide the floating navigation bar
Copy the code

If you have any experience with asynchronous programming, you should know that both methods are done simultaneously.

The order in which they are written does not affect the order in which they are executed

// Asynchronous operations do not interrupt the current program execution

// After the getUsers request is issued, the second request is immediately followed up

ajax("/getUsers".function(data) {

      // The callback function is called after the request succeeds

})

//resumelist requests start immediately, regardless of whether getUsers ends

ajax("/resumelist".function(data) {})The order in which the code is written is uncertain as to which Ajax will return the result first and execute the callback function.
Copy the code

We can make a simple definition of asynchronous operations

When an operation has started, the main program does not wait for it to complete and can continue to execute. The operation can then be synchronized with the main program and called an asynchronous operation. Usually when the operation is complete, we execute a preset callback function for subsequent processing. Time (concurrent) execution. This operation we

Common asynchronous operations are:


What are the problems with asynchrony?

For example, we now have two animations that need to be executed in order, i.e. the first one ends and the second one starts

This might be a bit of a hassle, but the traditional solution is to call back:

animateA(function( ){

      animateB( );     

})       
Copy the code

This scenario is obviously not a good one, and if you have a lot of asynchronous operations that need to be executed sequentially, you can have what’s called callback hell

ajaxA(function( ){

      ajaxB(function( ){

             ajaxC(function( ){

                    ajaxD(function( ){... }); }); }); })Copy the code

This kind of code is annoying to write and read. Let’s take a look at what Promise looks like after it’s transformed (pseudocode)

new Promise(ajaxA)

        .then(ajaxB)

        .then(ajaxC)

        .then(ajaxD);     
Copy the code

The use and principle of Promise

To use Promise proficiently, you must first understand how it solves problems

Post an actual Promise code to get a feel for it:

newPromise(resolve= >{
      ajax("/pay/post".data= >resolve() );
}).then(resolve= >{
      ajax("/order/fix".data= >{
            // Process data})})Copy the code

The above code uses the arrow function of ES6, which makes writing code much simpler, but is extremely unfriendly to beginners

Reading this code is like reading the Diamond Sutra. Let’s restore the code to ES5


new Promise(function(resolve){
      ajax("/pay/post".function(data){
            resolve();
      })
}).then(function(){
      ajax("/order/fix".function(data){})})Copy the code

So let’s go through the Feynman technique step by step how does Promise solve this problem

Question 1: Given an asynchronous function, especially a web request like Ajax, where I’m not even sure when the function will execute, how does Promise know when the first function ends? And then start executing the next one?

Promise isn’t that magical. It doesn’t know when our function ends. Did you notice line 3 in the code above

The key is to call the resolve() function at the end of the Ajax request to execute the callback.

This is basically telling Promise that this function is done, and you can start executing the next one. Then the Promise will execute the function inside then.

Question 2: So if I don’t call this method, Promise doesn’t know if the function ends, and then the function doesn’t execute, meaning my second request will never be sent?

Bingo!! Congratulations, you have learned logical reasoning + quick answer.

Question 3: But where does resolve come from? Do I need to define it myself? It looks like an argument from the code, but who passed it into the function?

You need to understand the basic structure of promises first

new Promise(function1). Then (function2);
Copy the code

We passed 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 is executed, the parameters are of course passed in by the Promise object.

new Promise(function(resolve){       //resolve is the argument that the Promise object passes when calling the function}). Then (function 2);
Copy the code

Q4. Why does the Promise object pass resolve on its first task?

What do you say?

Shit. Why would I ask you that?

What a pig’s brain. Didn’t we just say that? The Promise object has no way of knowing when our asynchronous function ends. Let me ask you something. If you pick someone up at the station and you don’t know when they get off, what would you do?

Give him my number and call me when you get there

Yes, Promise took the same approach to solving problems. It passes in the resolve function, which acts like a walkie-talkie to inform the Promise object when our asynchronous task is about to end. That is, call the resolve method

new Promise(function(resolve){
      ajax("/pay/post".function(data){
            // When the request ends, notify the Promise object that the task is complete by calling the resolve method
            resolve();
            // Upon receiving the notification, the Promise will immediately begin the execution of function 2})}). Then (function2);
Copy the code

Okay, so the resolve function, which must be called at the end of an asynchronous task (such as an Ajax callback method), essentially tells the Promise object that the task is done, please move on to the next one.

Absolutely right

Question 5. So Promise is nothing more than that. It doesn’t revolutionize functionality, because it works just as well using traditional nested callbacks. To put it bluntly, it is an improvement in the way coding is done.

That’s basically true, but the advances in coding and asynchronous programming that Promise brought were huge.

Question 6. So if I have three asynchronous tasks ajaxA, ajaxB, and ajaxC, and I want to execute them in the order A, B, and C, do I write them like this?

no

Depend! I haven’t told you yet!

That you said

What if I write it like this?


new Promise(function(resolve){
      ajax("/AAA".function(){
            resolve(); // Notify Promise that the task is over
      })    
}).then(function(resolve){
      ajax("/BBB".function(){
            resolve();// Notify Promise that the task is over
      })
}).then(function(){
      ajax("/CCC".function(){ //.... })
})   
Copy the code

This is not the right way to write it. The Chinese meaning of Promise is “Promise”, which means that each Pormise object represents a Promise

And each commitment can only guarantee the order of one task, which means

new Promise(A).then(B); The order of A and B can only be guaranteed.

Once A completes and B begins, the Promise is fulfilled and the Promise object is no longer valid

What if we have C? We then have to create a new Promise object in function B to fulfill the next Promise, written like this:


new Promise(function1(resolve){
      ajaxA("xxxx".function(){
             resolve();// Notify Promise that the task is over})}). Then (function2() {// After function 2 starts running, the Promise object that was first created completes its mission and can no longer work.
      // At this point, we create and return a new Promise object
      return new Promise(function(resolve){
             ajaxB("xxxx".function(){
                   resolve();// Notify the new Promise object that the task is over})})}).then(function3() {// The new Promise object is responsible for executing function 3, despite the chained call
      
       // If, we still have ajaxD to call sequentially
       // Then you must re-create the new Promise() object here
      ajaxC("xxx".function(){})})Copy the code

Question 7. Got it. What other powerful features does Promise have?

Yes, for example, if I have three asynchronous tasks A, B, and C, ABC starts executing at the same time

When task A,B, and C are all done and task D is done, the traditional approach is more complicated to implement, and promises are very simple, like this:

Promise.all([new Promise(A), new Promise(B), new Promise(C)]).then(function(){ D(); });Copy the code

Question 8. What if I want one of the tasks A,B, and C to complete and start task D immediately?

Promise.race([new Promise(A), new Promise(B), new Promise(C)]).then(function(){ D(); });Copy the code

Congratulations, you learned Promise in such a short time