Ruan Yifeng "ECMAScript 6 Getting Started" study notes --Promise

A, Promise meaning

Promise is asynchronous programming a solution than traditional solutions - more rational and more powerful - callback functions and events. It was first proposed and implemented by the community, ES6 be written into the standard language, unified usage, native in the Promiseobject.

The so-called 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.

PromiseObject has the following two characteristics.

State (1) is not subject to outside influence. PromiseObject represents an asynchronous operation, there are three states: pending(ongoing), fulfilled(been successful) and rejected(failed). Only results of asynchronous operations, you can decide what kind of current state, no other operations can change that state. This is also Promisethe origin of the name, which in English means "commitment", he said other means can not be changed.

(2) Once the status change, will not change, at any time this result can be obtained. PromiseState of the object changes, only two possibilities: from pendingchanges to fulfilledand from pendingturns rejected. As long as these two things happens on the solidification state, it will not be changed and will keep the result, then called resolved (finalized). If the change has occurred, you again Promiseadd an object callback function will immediately get this result. This event (Event) is completely different, the characteristics of the event is, if you missed it, go listen, it is not the result.

Note that, in order to facilitate the drafting, later in this chapter resolvedunified refers only to fulfilledthe state, it does not contain the rejectedstate.

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.

PromiseThere are also some disadvantages. First of all, can not be canceled Promise, it will be executed immediately once the new can not be canceled midway. Secondly, if you do not set a callback function, Promiseinternal error thrown, it does not react to the outside. Third, when in the pendingstate, progress is currently no way of knowing where a stage (beginning or nearing completion).

If certain events continue to occur repeatedly, in general, use Stream  mode than to deploy a better choice. Promise

Second, the basic usage

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

  IF ( / * successful asynchronous operation * / ) {
    resolve(value);
  } else {
    reject(error);
  }
});

resolveFunction returns the Promiseobject's state from "not completed" 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; rejectfunction returns It is the Promisestate of an object from "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.

PromiseAfter the instance generation, you can thenspecify methods resolvedstate and a rejectedcallback status.

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.

The following is a Promisesimple example of the object.

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

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

console.log('Hi!');

// Promise
// Hi!
// resolved

三、Promise.prototype.then()

Examples of methods have then Promise, that is, the method is defined in the prototype object Promise.prototype. Its role is to add callback function for the state change Promise instance. The first argument of the callback function is Resolved state, the second parameter (optional) is the callback function Rejected state.

getJSON("/post/1.json").then(
    post => getJSON(post.commentURL)
).then(
    comments => console.log("Resolved: ", comments);
    err => console.log("Rejected: ", err);
);

四、Promise.prototype.catch()

Promise.prototype.catch is .then (null, rejection) alias, when a callback function for specifying an error occurs.

the getJSON ( "/ posts.json"). the then ( function (Posts) { 
     // ... 
}). the catch ( function (error) {
 // pretreatment a callback function runtime error 
    console.log ( 'occurs wrong '! , error);
});

Note: the following two equivalent wording

// 写法一
var promise = new Promise(function(resolve, reject) {
      try {
        throw new Error('test');
     } catch(e) {
         reject (e);
     }
});

promise.catch(function(error) {
    console.log(error);
}); 
// writing two var Promise = new new Promise ( function (Resolve, Reject) { reject(new Error('test')); }); promise.catch(function(error) { console.log(error); });

Role reject methods, equivalent to throw an error. If the state has become a Promise Resolved, then throw an error is invalid.

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 captured under a catch statement.

With the traditional try / catch block is a different code, specify a callback function if no error handling method with a catch, Promise error objects thrown to the outer code is not transmitted, i.e., nothing happens.

var someAsyncThing = function () {
       return  new new Promise ( function (Resolve, Reject) {
       // following line being given, because no declaration x 2); 
      Resolve (x + 2 );
     });
};
someAsyncThing().then(function() {
     console.log('everything is great');
});       

五、Promise.all()

A method for multiple instances Promise, Promise packaged into a new instance.

var Promise.all([p1, p2, p3]);

The above code, Promise.all method takes an array as an example parameter, p1, p2, p3 are Promise object, if not, the following method is called Promise.resolve mentioned first, into the parameter Promise example, then further processing.

1) Only p1, p2, p3 have become Fulfilled state, the state will become a p fullfilled, this time p1, p2, p3 composed of an array of the return value, p is passed to the callback function.

2) As long as p1, p2, p3 Rejected is a state, the state will become the p Rejected, return values ​​at this time is the first instance of the reject, is passed to the callback function p.

// generates an array of objects Promise 
const Promises = [2,. 3,. 5,. 7,. 11, 13 is] .map ( function (ID) {
   return the getJSON ( '/ POST /' + ID + ".json" );
});

Promise.all(promises).then(function (posts) {
  // ...
}).catch(function(reason){
  // ...
});
六、Promise.race()

The method also Promise.race multiple instances Promise, Promise packaged into a new instance.

var p = Promise.race([p1,p2,p3]);

The above code, as long as one example among p1, p2, p3 lead changes state, the state will change with p. Promise to return the value of that instance of the first to change, it is passed to the callback function p.

七、Promise.resolve()

Sometimes you need to turn existing objects Promise objects, resolve method to play this role.

var jsPromise = Promise.resolve($.ajax('/whatever.json')); 

(1) is a parameter instance Promise

Without any modification, is returned unchanged this instance.

(2) is a parameter (i.e., an object having the method then) a target thenable

Promise that object into an object, then immediately execute then the method of the object.

(3) parameter is not an object then the method, or simply not an object

Promise method returns a new object state Resolved

(4) no parameters (corresponding to promise a new object)

var p = Promise.resolve();
    p.then(function () { // ...
});

八、Promise.reject()

The method also returns a new Promise instance, the instance state is rejected. It uses exactly the same arguments and Promise.resolve method.

Nine, done () and finally ()

Callback chain Promise object, regardless of method or ending then catch method, a method throws an error if the last, there may not be captured (because of internal errors do not bubble up to the Global Promise). Therefore, we can provide a method done, always at the end of the callback chain, ensuring throw any errors that may occur.

Seen from the above code, the method used done, as can be used, and rejected states fullfilled provide callback function, or may not then provide any parameters like method. In any case, done will catch any errors that may occur, and throw the global.

Regardless of the method used to target Promise final state, the operation will be performed specified. It is done with the method of the biggest difference, it takes an ordinary callback function as a parameter, the function must be performed anyway.

 

Guess you like

Origin www.cnblogs.com/fmyao/p/12604296.html