ES6 knowledge -Promise objects

4.3Promise objects

4.3.1Promise Overview

  • Promise is asynchronous programming a solution .
  • Promise to solve multiple nested callbacks proposed.
  • It is not new syntax features, but a new wording allows the callback function nesting , into chained calls .
  • Promise is a subject , it may be from the acquired message asynchronous operation .
  • Promise provide uniform the API , a variety of asynchronous operations are treated in the same manner .
  • Promise has the following two characteristics:
    • Object of the state against external influences . Promise object represents an asynchronous operation , there are three states: the Pending (in progress), to Resolved (has been completed, also known Fulfilled) and Rejected (failed).
    • Once the status change, it will not change any time can get this result. Promise object state changes , only two possibilities : from Pending changes to Resolved and from Pending changes to Rejected .
  • Promise also has some drawbacks:
    • You can not cancel Promise , it will be executed immediately once the new can not be canceled midway.
    • If you do not set a callback function , internal Promise thrown error, it does not react to the outside .
    • While in Pending status, we can not know the current progress where a stage ( just starting or nearing completion).

4.3.3 Operation Ajax achieved using Promise

var getData = function(url) {
  var promise = new Promise(function(resolve, reject){
    var client = new XMLHttpRequest();        // 封装请求对象
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();
    function handler() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);         // 请求成功执行
      } else {
        reject(new Error(this.statusText));        // 请求失败执行
      }
    };
  });
  return promise;
};
getData("/posts/info")

    .then(

        function(json) {console.log('Contents: ' + json);}, 

        function(error) {console.error('出错了', error);}

    );
  • When called with parameters resolve function and reject functions, then their argument will be passed to the callback function.

4.3.4 Basic Usage

  • ES6 predetermined, Promise objects is a constructor , to generate Promise instance .

  • Promise constructor takes a function as a parameter , the two parameters of the function are resolve and Reject . They are two functions provided by the JavaScript engine, you do not have to deploy.
  • resolve function effect is the Promise object state from "not completed" to "success" (i.e., changes from the Pending to Resolved) , and calls upon successful asynchronous operation asynchronous operation results, to pass out as a parameter .
  • reject function effect is the Promise object state from "not completed" to "failed" (i.e., changes from the Rejected Pending) , asynchronous invocation and operation failure when an asynchronous operation of reported errors, to pass out as a parameter .

var promise = new Promise(function(resolve, reject) {
  if (true){
    resolve(value);
  } else {
    reject(error);
  }
});

4.3.5then method

  • then the method returns is a new example of Promise (note, not the original that Promise instance).
  • Thus it can be written using the chain , i.e., the method then back again then invoke another method .
//第一个then方法指定的回调函数,返回的是另一个Promise对象。
//第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。
//如果变为Resolved,就调用funcA,如果状态变为Rejected,就调用funcB。
getData("/get/info")
    .then(function(get) {return getData(get.commentURL);})
    .then(
        function funcA(comments) {console.log("Resolved: ", comments);}, 
        function funcB(err){console.log("Rejected: ", err);}
    );
//箭头函数简写
getData("/get/info")
    .then(  get => getData(get.commentURL  ))
    .then(
        comments => console.log("Resolved: ", comments),
        err => console.log("Rejected: ", err)
    ); 

4.3.6catch method

  • Promise.prototype.catch method. The then (null, rejection) of aliases

  • It is used to specify a callback function when an error occurs .

  • then the method specified callback function, if the operation throws an error will be captured catch method .

    p.then((val) => console.log("fulfilled:", val))
      .catch((err) => console.log("rejected:", err));
    // 等同于
    p.then((val) => console.log("fulfilled:", val))
      .then(null, (err) => console.log("rejected:", err));

4.3.7done () method

  • Callback chain Promise object, regardless of the method to then still catch the end of the method, if the last method throws an error , you may not be able to capture (because of internal errors do not bubble up to the Global Promise)

  • A done method , always at the end of the callback chain to ensure that throw any errors that may occur .

    Promise.prototype.done = function (onFulfilled, onRejected) {
      this.then(onFulfilled, onRejected)
        .catch(function (err) {
          // 抛出一个全局错误
          setTimeout(() => { throw err }, 0);
        });
    };

Guess you like

Origin www.cnblogs.com/xuzhengguo/p/12057019.html