I have written some articles about the basic uses of promise, but I don’t have a deeper understanding of promise. I hope I can introduce it more clearly.

Almost everything I’ve done since then has been in javaScript Mid-Volume you Don’t Know

Promise I understood

We all know that Promise solved callback hell, and I always thought it solved callback readability, nesting, and maintenance problems

For example,

btn.addEventListener('click', function () { setTimeout(function request() { ajax("http://some.url.1", function response(text) { if (text == "hello") { handler(); } else if (text == "world") { request(); }}); }, 500); })Copy the code

This is listening for button click events, followed by timers, followed by Ajax requests

The script is not readable, the three functions are nested together, and the logic is difficult to reuse

With the promise of writing

function listen() {
      return new Promise(function (resolve, reject) {
        btn.addEventListener('click', function () {
          resolve()
        })
      })
    }

    function request() {
      return new Promise(function (resolve, reject) {
        setTimeout(() => {
          resolve()
        }, 500);
      })
    }

    function ajax() {
      return new Promise(function (resolve, reject) {
        ajax("http://some.url.1", function response(text) {
          if (text == "hello") {
            resolve()
          }
          else if (text == "world") {
            reject()
          }
        });
      })

    }

    listen().then(function(){
      return request()
    }).then(function(){
      return ajax()
    }).then(function(result){
      
    })
Copy the code

After rewriting with promise, each method function is clear, and each method can be reused after good readability

But Promise doesn’t just address these issues

The callback problem

Listen to the story

To see what’s wrong with callbacks, take a look at an example from javaScript you Didn’t Know

Suppose you’re a developer building a business checkout system for a website that sells expensive TVS. You have all the interfaces of the settlement system in place. On the last page, when a user clicks “OK” to buy a TV, you need to call a third-party function (presumably provided by an analytics tracking company) to track the transaction. You notice, probably to improve performance, that they provide a tool that looks like it’s used for asynchronous tracing, which means you need to pass in a callback function. In the continuation that comes in, you need to provide the final code to charge the customer and display the thank you page. The code might look like this:

analytics.trackPurchase( purchaseData, function(){ chargeCreditCard(); displayThankyouPage(); });Copy the code

Simple, isn’t it? You write the code, you test it, everything works, and you deploy the product. Everybody’s happy!

Six months have passed without any problems. You almost forgot you wrote it. One morning before work, you’re enjoying a latte in a cafe as usual. Suddenly, in a panic, your boss calls and tells you to put down your coffee and hurry to the office.

When you arrive at the office, you are understandably upset to learn that one of your top customers has been charged five times on his credit card after buying a TELEVISION. The customer service has apologized and started the refund process. But your boss needs to know why this is happening. “Haven’t you tested for that? !” You don’t even remember writing this code. However, you need to drill down into the code and start looking for the cause of the problem.

By analyzing the log, you conclude that the only explanation is that the analysis tool for some reason called your callback five times instead of once. There is no mention of this in their documentation.

Frustrated, you contact their customer service, who is clearly as surprised as you are. They promise to submit it to the developers and get back to you. The next day, you receive a long letter explaining their findings, which you immediately forward to your boss.

Apparently, the analytics company’s developers developed some experimental code that, in some cases, would try the incoming callback once a second for five seconds before it failed due to timeout. They never intended to put this code into production, but somehow they did, and they were embarrassed and apologetic. They explained at length how they had determined what had gone wrong, promised that it would never happen again, and so on.

And then what? You discuss it with your boss, who isn’t too happy with the situation. You can’t trust them anymore, he insists. You just have to live with that, and you need to find some way to protect the checkout code so that the certificate doesn’t break again. After tinkering, you implement simple temporary code like this, and everyone seems happy:

var tracked = false; analytics.trackPurchase( purchaseData, function(){ if (! tracked) { tracked = true; chargeCreditCard(); displayThankyouPage(); }});Copy the code

Later, however, a QA engineer asked, “What if they don’t call this callback at all?” Ouch! Neither of you thought of that before.

Then you start digging down the rabbit hole, thinking about all the ways they could go wrong when they call your callback. Here’s a rough list of things you can think of that could go wrong with an analytics tool:

  • Call the callback too early (before tracing);

  • Calling the callback too late (or not called);

  • Too few or too many callbacks (as you’ve had!) ;

  • Does not pass the required environment/parameters successfully to your callback function;

  • Swallow possible errors or exceptions;

•…

That’s the end of the story

The story is over and the problem needs to be solved

The problem with the story is that a third-party tool calls your callback function five times, and while it fixes the problem with a variable control, there is no guarantee that there will be another problem

The callback problem

The biggest problem with callbacks is inversion of control. Inversion of control means that the callback functions are in your own code, but passing the callback functions to a third party tool gives control of the callback to a third party, just like the problem in the story

But the callback itself does not provide a solution to these problems,

Promises are specifically designed to provide a valid, reusable answer to these questions.

Promise

To solve the problem

So let’s solve the following problems one at a time

  • Call the callback too early (before tracing);

  • Calling the callback too late (or not called);

  • Too few or too many callbacks (as you’ve had!) ;

  • Does not pass the required environment/parameters successfully to your callback function;

  • Swallow possible errors or exceptions;

Calling the callback too early

Let’s look at an example

function result(data) { console.log( a ); } var a = 0; ajax( ".. pre-cached-url.." , result ); a++;Copy the code

This code prints a 1 or a 0 depending on whether Ajax is synchronous or asynchronous. If it’s synchronous, print a 0 or print a 1 asynchronously. If you want your callback to be executed asynchronously, but a third-party Ajax does synchronize the API, this will result in the output not being what it’s supposed to be.

And Promise solved that problem,

function result(data) { let pormise = new Promise(function(resolve,reject){ resolve(a) }) return promise } var a = 0; ajax( ".. pre-cached-url.." , result ); a++;Copy the code

At this point, the callback must be executed asynchronously and the print must be 1

Call several times

A promise can only be resolved once, and the state changes and never changes again

The callback is not called

We can use the promise race

Function timeoutPromise(delay) {return new Promise(function(resolve,reject){setTimeout())  function(){ reject( "Timeout!" ); }, delay ); }); } // Set foo() timeout promise.race ([foo(), // Try to start foo() timeoutPromise(3000) // give it 3 seconds]).then(function(){// foo(..) Finish in time! }, function(err){// either foo() was rejected, or just didn't finish on time // Check err to see which case});Copy the code

After some problems did not write solutions, then fill up, or directly read a book