Promise objects] [ECMAScript6

Promise, It simply is a container, which holds the event will end sometime in the future (usually an asynchronous operation) results. Syntactically, Promise is an object, you can get messages from the asynchronous operation of it. Promise to provide a unified API, a variety of asynchronous operations can be handled the same way.

With Promisethe object can be asynchronous operation to synchronous operation flow express avoided deeply nested callback function. Further, Promisean object to provide a unified interface, so that the control asynchronous operations easier.

First, the basic usage

ES6 predetermined, Promise object is a constructor to generate Promise instance.

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

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

Promise constructor takes a function as a parameter, two parameters are the function resolve and reject. They are two functions provided by the JavaScript engine, you do not have to deploy.

Function is to resolve the role of the state of the object from Promise "unfinished" to "success" (i.e., changed from pending resolved), upon successful call asynchronous operation, and the result of the asynchronous operation, to pass out as a parameter;

Function is to reject the role of the state of the object from Promise "unfinished" to "failed" (i.e., changed from pending Rejected), invoked when an asynchronous operation fails, and the asynchronous operation errors may be, as a parameter to pass out .

After generating Promise example, you can specify a callback function resolved state by state and then rejected Methods.

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

thenThe method can accept two callback functions as arguments. The first callback is Promisestate of the object into a resolvedcall, the callback function is the second Promisestate of the object becomes rejectedcalled. Wherein the second function is optional and not required to provide. Both functions accept the Promisevalue of the object as a parameter spread.

Two, then () method

Promise instance has thenmethods, i.e., thenmethods in the prototype object is defined Promise.prototypeon. Its role is to add callback function for the state change Promise instance. As mentioned above, thenthe first argument of the method is resolveda callback function of the state, and the second parameter (optional) is the rejectedcallback status.

thenMethod returns a new Promiseinstance (note, not the original Promiseinstance). It can be written using the chain, i.e. thenafter the method then calls another thenmethod.

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});

Three, catch () method

Promise.prototype.catchMethod .then(null, rejection)or .then(undefined, rejection)alias for the specified callback function an error occurs.

getJSON ( '/ posts.json'). the then ( function (Posts) {
   // ... 
}). the catch ( function (error) {
   // an error occurred while processing a previous callback getJSON and run 
  console.log ( 'error occurs!' , error); 
});

If the state has become Promise resolved, then throw an error is invalid.

the getJSON ( '/ POST / 1.json') the then. ( function (POST) {
   return the getJSON (post.commentURL); 
.}) the then ( function (Comments) {
   // some code 
.}) the catch ( function (error) {
   // processing error generated in front of three Promise 
});

Promise error object has a "bubble" in nature, it will always back pass, until it is captured so far. In other words, the error will always be the next catchstatement capture.

the getJSON ( '/ POST / 1.json') the then. ( function (POST) {
   return the getJSON (post.commentURL); 
.}) the then ( function (Comments) {
   // some code 
.}) the catch ( function (error) {
   // processing error generated in front of three Promise 
});

In general, do not thendefined inside a method callback Reject state (i.e., thenthe second argument) is always used catchmethod.

// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });

Four, finally () method

finallyRegardless of the method used to target Promise final state, the operation will be performed specified. The standard method is introduced ES2018.

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});

finally realized:

Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value  => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};

Five, all () method

 

Guess you like

Origin www.cnblogs.com/myitnews/p/12191936.html