Common cases of es6 promise objects

ES6 specifies that a Promise object is a constructor that generates a Promise instance.

//创造一个Promise实例
const promise = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

The function of the resolve function is to change the status of the Promise object from "uncompleted" to "successful" (that is, from pending to resolved), to be called when the asynchronous operation is successful, and to pass the result of the asynchronous operation as a parameter; reject The function of the function is to change the state of the Promise object from "unfinished" to "failed" (that is, from pending to rejected), to be called when the asynchronous operation fails, and to pass the error reported by the asynchronous operation as a parameter.
write picture description here
After the Promise instance is generated, the then method can be used to specify the callback function of the resolved state and the rejected state respectively.

promise.then(function(value) {
  // success
}, function(error) {
  // failure
});

The then method can accept two callback functions as parameters. The first callback function is called when the state of the Promise object becomes resolved, and the second callback function is called when the state of the Promise object becomes rejected. Among them, the second function is optional and does not have to be provided. Both of these functions accept the value passed from the Promise object as a parameter.

Example of asynchronously loading images

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;
  });
}
//函数调用
loadImageAsync('7.png').then((image)=>{
    console.log(image)
},(e)=>{
    console.log(e)
})

Ajax operations implemented with Promise objects

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('出错了', error);
});

p1 is a Promise that becomes rejected after 3 seconds. The state of p2 changes after 1 second, and the resolve method returns p1. Since p2 returns another Promise, the state of p2 itself is invalid, and the state of p1 determines the state of p2. Therefore, the following then statements all become for the latter (p1). After another 2 seconds, p1 becomes rejected, causing the callback function specified by the catch method to be triggered.

const p1 = new Promise(function (resolve, reject) {
  setTimeout(() => reject('我先'), 3000)
})
const p2 = new Promise(function (resolve, reject) {
  setTimeout(() => resolve(p1), 1000)
})
p2.then(result => console.log('result',result),reject=>console.log('reject',reject))
.catch(error => console.log('error',error))

The result is: reject me first

$.ajax({
    url: '......',
    success: function (data) {
        $.ajax({
            // 要在第一个请求成功后才可以执行下一步
            url: '......',
            success: function (data) {
                 // ......
            }
        });
    }
});

Promises can solve the above layer-by-layer callback situation very well.

But it still has compatibility issues
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325376153&siteId=291194637