Prometheus stealing fire


Asynchronous function Promise

Personally, I think the Promise function is a lot like Prometheus, a prophet who deals with the future. Since it can handle things in the future, that means it has a very strong ability, listen to me slowly.

A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations. Promise provides a uniform API, and all kinds of asynchronous operations can be handled in the same way.

Isn’t that right? Doesn’t it look like a prophet who can handle the future? Since is immortal affirmation is we mortal tube not of, why tube not that? This is reflected in its three internal states:

The status of an object is not affected. The Promise object represents an asynchronous operation with three states: Pending, fulfilled and Rejected. Only the result of the asynchronous operation can determine the current state. No other operation can change this state. That’s where the name “Promise” comes from. Its English name means “Promise,” indicating that nothing else can change it.

See? You can’t change what the gods have decided. And once the new Promise object can not be cancelled, pay attention to ~

So how do you use that? Here’s a simple example:

const promise = new Promise (function(resolve, reject) {// This is a prophet, prophetifResolve (value); // If the prophet agrees, you are done!else{ reject(error); // reject (reject);Copy the code

Notice if the above thing actually happened? No prophet, predict the future, when did it happen? And of course when the prophet says yes it becomes resolved. Just as soon as it’s resolved, then that’s what it is.

promise.then(function(value) {// This is done. What do you want to do next? You can operate indefinitelythenGo down},function(error) {// Failed to print out the error message console.log(Error message:+error)
});
Copy the code

So here’s the trick. Look at the code below. Who prints first?

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

promise.then(function() {
  console.log('resolved.');
});

console.log('Hi! ');
Copy the code

In the code above, the Promise is executed immediately after it is created, so the Promise is printed first. Then, the callback specified by the then method will not execute until all synchronization tasks in the current script have finished, so resolved will output. So this next paragraph


Concept blown out, look at power

Ok, let’s look at an example of an Ajax operation implemented with a Promise object:

const getJSON = function(url) { 
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if(this.readyState ! = = 4) {return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else{ reject(new Error(this.statusText)); }}; const client = new XMLHttpRequest(); client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept"."application/json");
    client.send();

  });

  return promise;
};

getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('Wrong', error);
});
Copy the code

Is it very simple, not difficult, just put the Ajax operation process into the wevin internal, let wevin help you get all kinds of success and failure of the state! Given the fact that we may have to request data from several interfaces at a time at work, Promise offers a simpler approach

const p = Promise.all([p1, p2, p3]);
Copy the code

The parameter “all” represents an executable task queue, which can be executed as long as there are tasks in it. This is an array of apis that we access.

// Generate an array of Promise objects const Promises = [2, 3, 5, 7, 11, 13]. Map (function (id) {
  return getJSON('/post/' + id + ".json"); //ID becomes a dynamic request}); Promise.all(promises).then(function (posts) {
  // ...
}).catch(function(reason){
  // ...
});
Copy the code

The Promise. Race method takes the same parameters as the promise. all method. If it is not a Promise instance, the Promise. Turn the parameters into a Promise instance and proceed further

const p = Promise.race([
  fetch('/resource-that-may-take-a-while'),
  new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('request timeout')), 5000)})]); p .then(console.log) .catch(console.error);Copy the code

In the code above, if the fetch method fails to return a result within 5 seconds, the status of the variable P changes to Rejected, which triggers the callback specified by the catch method.

No problem. Now that I’m here, I’m sure you get the idea that any technique is not difficult and can be broken down into several simple points. The combination of any simple points will be complicated again. It is the so-called simple road. I believe that everything is a simple principle, and I will learn with awe, and I will eventually get my harvest.