What is thePromise?

  • One of the most important and useful features in ES6 is Promise
    • But on first contact, Promise is like, “What the hell is this?”
    • Look at the official or some articles on its introduction and usage, but also confused.
  • What exactly does Promise do?
    • Promise is a solution to asynchronous programming.
  • So when do we handle asynchronous events?
    • A very common scenario would be a network request.
    • We encapsulate a network request function that can’t return the result as simple as 3+4=7 because we don’t get the result immediately.
    • So often we pass in another function that calls back the data when the data request succeeds.
    • If it is a simple network request, then this scheme will not cause us much trouble.
  • However, callback hell can occur when network requests are very complex.
    • OK, let me illustrate with a very exaggerated example.

Network request callback hell

  • Consider the following (exaggerated) scenario:
    • We need to load a data1 from the server via an URL1, which contains the URL2 of the next request
    • We need to fetch URl2 from data1 and load data2 from the server, which contains the URL3 of the next request
    • We need to fetch URL3 through datA2 and load data datA3 from the server, which contains urL4 for the next request
    • Send network request urL4 to obtain the final data datA4

Analysis: What’s wrong with the above code? Normally, there’s no problem, it works and it gets the results we want. However, such code is ugly and not easy to maintain. What we expect is a more elegant way to do this asynchronous operation. Promise can solve this problem in a very elegant way.

When do YOU use a Promise

  • Usually there isAsynchronous operations, use the promiseEncapsulate asynchronous operations
  • The incoming callback is executed with two arguments, resolve and reject, which are functions themselves
  • Promises separate network requests from processing code

Three states of Promise

There are three states after an asynchronous operation

  • Pending: The waiting state, such as network requests being made, or the timer has not reached the point
  • Fulfill (fulfill) : fulfill (fulfill) : fulfill (fulfill) : fulfill (fulfill) : fulfill (fulfill) : fulfill (fulfill)
  • Reject: The reject state, which we are in when we actively call reject and we call catch ()

Promise’s basic use

  • Let’s start with the basic syntax of promises.

  • Here, we use a timer to simulate an asynchronous event:

    • Suppose the following data is requested from the network after 1 second
    • Console. log is what we do.

  • The way we used to do it above, we replaced it with a Promise code

– This example makes us feel like we’re farting with our pants down

  • First, the Promise code below looks significantly more complex than the code above.

  • Second, what are the resolve, reject, then and catch elements contained in the Promise code below?

  • Let’s ignore the first complexity question, because such a big program would never see the Promise’s real impact.

Analysis of the

Let’s take a hard look at what this program does.

  • New Promise obviously creates a Promise object
  • The parenthesis ((resolve, reject) => {}) is also clearly a function, and we’re using the arrow function we learned earlier.
    • But resolve, reject what are they?
    • Let’s start with the fact that the arrow function passed in to create the Promise is fixed (as we would normally write)
    • Resolve and reject are also functionsNormally, we decide which one to call based on the success and failure of the request data.
  • Success or failure?
    • If it is successful, then usually we call resolve(messsage), at which point we follow upThen is called back.
    • If it fails, then we usually call Reject (error), and at that point, our nextThe catch is called back.

A chained call to a Promise

The flow chart of Promise

When we look at the flow chart of a Promise, we see that either a Then or a catch can return a Promise object. ยท So, our code is actually capable of chaining calls: here we simply wrap the new data with the Promise and return the Promise object.

  • Promise.resovle() : Wraps the data as a Promise object and calls back to the resolve() function internally
  • Promise.reject() : Wraps data as a Promise object and calls the reject() function internally

Simplified version

  • If we want the data to be wrapped directly as promise.resolve, we can return the data directly in the then

  • Note that in the code below, I said return promise.resovle (data) instead of return data. The result is still the same

By default, then and catch return a promise object. If you return the data directly, it will automatically wrap the Promise inside, equivalent to promise.solve (data)

We can throw an ‘error message’ when we want promise.reject (data). Both throw and reject callbacks are caught by catch.

Promise’s all method

Requirement scenario: When there are two or more network requests (the requirement depends on two or more requests to complete), the all method requires passing an iterable, which can be an array of objects

Promise. All (Iterator)Copy the code

Example requests using Ajax

<script>
 Promise.all([
   new Promise((resolve,reject) = >{
     // Ajax's first network request
     $ajax({
       url:' '.success:function(data){ resolve(data); }})}),new Promise((resolve,reject) = >{
    // Ajax's second network request
    $ajax({
       url:' '.success:function(data){
         resolve(data);
       }
     })
   })
 ]).then(resualts= >{
    console.log(results);
   The results is an array containing the returned data for all requests. The order is the code writing order, not the request success order
    
    
 })
// Results can also be deconstructed. It's just that array deconstruction is not very common, so you can see it
/ * then ((name1 name2) = > {}) or then ([name1, name] = > {}) * /


</script>
Copy the code