ES6 promise object — write asynchronous code like synchronous code


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.


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


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.


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.


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 * /){
  } else {

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) {

promise.then(function() {


// 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() {

    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) {
      if (this.status === 200) {
      } else {
        reject(new Error(this.statusText));
    const client = new XMLHttpRequest();"GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");


  return promise;

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


Universal network

Ruan Yifeng’s ES6 Grammar Course

And hard-working themselves,Personal blogGitHub

ES6 promise object -- write asynchronous code like synchronous code