ES6 Promise object – write asynchronous code like synchronous code

The blog instructions

The information involved in the article comes from the Internet collation and personal summary, meaning is the summary of personal learning and experience, if there is any infringement, please contact me to delete, thank you!

Introduction to the

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. In layman’s terms, promises are containers that hold the results of asynchronous operations.

The characteristics of

The status of an object is not affected

Promise objects have three states: Pending, fulfilled and Rejected.

Only the result of an asynchronous operation can determine the current state, and no other operation can change the state.

Once the state changes, it never changes again, and you can get this result at any time

There are only two possibilities for the state of the Promise object to change from pending to depressing and from pending to Rejected. As soon as these two things happen the state is fixed and will not change and will remain as it is called resolved.

Advantages and Disadvantages

advantages

1. The Promise object can express asynchronous operations in a synchronous operation process, and write asynchronous code in a synchronous way, avoiding layers of nested callback functions.

2. Promise objects provide a unified interface that makes it easier to control asynchronous operations.

disadvantages

1. You cannot cancel a Promise. Once a Promise is created, it will be executed immediately.

2. If you don’t set a callback function, errors thrown inside a Promise won’t be reflected outside.

Third, when in the pending state, there is no way to know what stage of progress is currently in (just started or nearly finished).

case

Promise instance

The Promise constructor takes a function as an argument, resolve and reject. Notice these are two functions.

const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* Asynchronous operation succeeded */){
    resolve(value);
  } else{ reject(error); }});Copy the code

The resolve function changes the state of the Promise object from “unfinished” to “successful.” It will be called when the asynchronous operation succeeds and will pass the result of the asynchronous operation as an argument.

The Reject function changes the state of the Promise object from “unfinished” to “failed” (i.e., from Pending to Rejected). It is called when the asynchronous operation fails and passes the error reported by the asynchronous operation as a parameter.

Promise execution order

Promises are implemented as soon as they are created.

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

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

console.log('33');

/ / 11
/ / 33
/ / 22
Copy the code

The Promise is executed immediately after it is created, so 11 is printed first. The callback specified by the then method is asynchronous and will not be executed until all synchronization tasks in the current script have been executed, so output 33,22, and last.

Example of loading images asynchronously

An asynchronous image loading operation is wrapped with Promise. If the load succeeds, the resolve method is called, otherwise the Reject method is called.

function loadImageAsync(url) {
  return new Promise(function(resolve, reject) {
    const image = new Image();

    image.onload = function() {
      resolve(image);
    };

    image.onerror = function() {
      reject(new Error('Could not load image at ' + url));
    };

    image.src = url;
  });
}
Copy the code
Ajax for the Promise object implementation

You wrap the XMLHttpRequest object in the getTest function, send an HTTP request, and get a Promise object.

const getTest = 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;
};


// Call the case
getTest("/test.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error(error);
});
Copy the code

Promise error handling

If the Promise state has changed to Resolved, throwing an error is invalid. Because once a Promise state changes, it stays that state forever.

Errors from the Promise object are bubbling and are passed backwards until they are caught. That is, an error is always caught by the next catch statement.

const promise = new Promise(function(resolve, reject) {
  resolve('ok');
  throw new Error('test');
});
promise
  .then(function(value) { console.log(value) })
  .catch(function(error) { console.log(error) });
// ok
Copy the code

Thank you

Universal network

Ruan Yifeng es6 grammar tutorial

And hard-working self, personal blog, GitHub