ES6 promise object — write asynchronous code like synchronous code

Time:2022-1-14

ES6 promise object — write asynchronous code like synchronous code

Blog description

The information involved in this article comes from the Internet and personal summary, which means the summary of personal learning and experience. If there is any infringement, please contact me to delete it. Thank you!

brief introduction

Syntactically speaking, promise is an object from which you can get the message of asynchronous operation. Promise provides a unified API, and various asynchronous operations can be processed in the same way. Generally speaking, promise is a container that holds the results of asynchronous operations.

characteristic

The state of the object is not affected by the outside world

PromiseObjects have three states:pending(in progress)fulfilled(successfully) andrejected(failed).

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

Once the state changes, it will not change again. This result can be obtained at any time

PromiseThere are only two possibilities for the state of an object to change: frompendingBecomefulfilledAnd frompendingBecomerejected。 As long as these two situations occur, the state will solidify, will not change, and will always maintain this result. At this time, it is called resolved.

Advantages and disadvantages

advantage

1、PromiseObject can express asynchronous operation in the process of synchronous operation, and write asynchronous code in a synchronous way, avoiding nested callback functions.

2、PromiseObject provides a unified interface, which makes it easier to control asynchronous operations.

shortcoming

1. Cannot cancelPromise, once it is created, it will be executed immediately and cannot be cancelled halfway.

2. If the callback function is not set,PromiseErrors thrown internally will not be reflected externally.

3. Third, when inpendingIt is impossible to know which stage (just started or about to be completed) the current progress has reached.

case

Promise instance

PromiseThe constructor takes a function as a parameter, and the two parameters of the function areresolveandreject。 Notice that these are two functions.

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

  If (/ * asynchronous operation succeeded * /){
    resolve(value);
  } else {
    reject(error);
  }
});

resolveThePromiseThe status of the object changes from “incomplete” to “successful” (that is, from pending to resolved). It is called when the asynchronous operation is successful, and the result of the asynchronous operation is passed as a parameter;

rejectThePromiseThe state of the object changes from incomplete to failed (that is, from pending to rejected). It is called when the asynchronous operation fails, and the error reported by the asynchronous operation is passed as a parameter.

Promise execution sequence

PromiseThe new will be executed immediately.

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

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

console.log('33');

// 11
// 33
// 22

Promise is executed immediately after it is created, so the first output is11thenThe callback function specified by the method is an asynchronous function and will not be executed until all synchronous tasks in the current script are executed, so the output3322Final output.

Asynchronously loading picture cases

usePromiseWrapped an asynchronous operation of image loading. If the load is successful, callresolveMethod, otherwise it is calledrejectmethod.

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;
  });
}
Ajax implemented by promise object

staygetTestFunction encapsulates the XMLHttpRequest object, sends an HTTP request, and gets anPromiseObject.

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 case
getTest("/test.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error(error);
});

Promise error handling

If promise status has changed toresolved, it is invalid to throw an error again. Because once the promise state changes, it will remain in this state forever and will not change again.

Error with promise objectBubblingProperty is passed back until it is captured. In other words, mistakes will always be made by the next onecatchStatement capture.

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

thank

Universal network

Ruan Yifeng’s ES6 Grammar Course

And hard-working themselves,Personal blogGitHub

ES6 promise object -- write asynchronous code like synchronous code