es6 study 3: promise

promise meanings:

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.

 

promise basic usage:

PromiseConstructor takes a function as a parameter, two parameters of the function are respectively resolveand 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 .

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

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

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

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

 

After the new promise will be executed immediately

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

promise.then(function() {
   console.log('resolved result');
});
for(var i=0;i<100;i++) {
  console.log(i);
}
/* Promise instance 1 2 3 ... 99 100 resolved result */

 

resolveAddition to the normal function of the parameters values, but also may be another example of Promise, such like this.

const p1 = new Promise(function (resolve, reject) {
  // ...
});

const p2 = new Promise(function (resolve, reject) {
  // ...
  resolve(p1);
})

The above code, p1and p2are examples of Promise, but p2the resolvemethod p1as a parameter, i.e. a result of the asynchronous operation is another return asynchronous operation.

Note that at this time p1the state will transfer to p2, say, p1the state determines the p2state. If the p1state is pending, then the p2callback function will wait for p1a change of state; if p1the state is already resolvedor rejected, the p2callback function will be executed immediately.

 

promise.prototype,then()

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) {
  // ...
});

The above code uses the thenmethod, the two callback functions specified sequence. After the first callback is completed, the result will be returned as a parameter passed in the second callback.

The use of the chain then, you can specify a set of callback functions in the order called. At this time, before a callback function, there is still a possible return of Promisethe object (that is asynchronous operation), then after a callback function, it will wait for the Promiseobject's status changes, will be called.

getJSON("/post/1.json").then(function(post) {
  return getJSON(post.commentURL);
}).then(function (comments) {
  console.log("resolved: ", comments);
}, function (err){
  console.log("rejected: ", err);
});

In the above code, the first thenmethod specified callback function returns another Promiseobject. At this time, the second thenmethod specified callback function will wait for the new Promiseobject state changes. If changed resolved, it calls the first callback, if the status changes rejected, call the second callback function.

If the function of the arrow, the above code can be written more succinctly. 
the getJSON (
"/post/1.json" ) .then (
POST
=> the getJSON (post.commentURL) ) .then (
Comments
=> the console.log ( "resolved:" , Comments), ERR => the console.log ( " Rejected: " , ERR) );

 

promise.prototype.catch()

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); });

In the above code, the getJSON method returns a Promise object, if the object status becomes resolved, then the method specified callback function will be called;

If the asynchronous operation throws an error, status changes rejected, will call the catch method specified callback function, to deal with this error. In addition, then the method specified callback function, if the operation throws an error, it will be caught 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));

 

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
  });

In the above code, the second writing is better than the first writing, writing is the second reason can capture the foregoing thenmethod performed errors, are closer to synchronous writing ( try/catch). It is therefore recommended to always use catchthe method, instead of using the thenmethod of the second parameter.

 

promise.protype.finally

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(() => {···});

 

promise.all

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

const p = Promise.all([p1, p2, p3]);

The above code, the Promise.allmethod takes an array as a parameter, p1, p2, p3are examples Promise, if not, the following will be called first mentioned Promise.resolvemethod, the parameter into Promise instance, further processing. ( Promise.allMethod parameters may not be an array, but must have the Iterator interface, and each member is returned Promise instance.)

pState by the p1, p2, p3determined, is divided into two cases.

(1) Only p1, p2, p3is turned into a state fulfilled, pthe state will become a fulfilledthis case p1, p2, p3the return value consisting of an array, is passed to the pcallback function.

(2) long p1, p2, p3being there is to be a rejected, pa state becomes rejected, the first case is rejectthe return value of the instance, is passed to the pcallback function.

 

promise.race()

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

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

In the above code, as long as p1, p2, p3in one instance first to change state, pthe state will change accordingly. Promise to return the value of that instance of the first to change, it is passed to the pcallback function.

Promise.raceParameters and methods Promise.allthe same way, if not Promise instance, it will first call the below mentioned Promise.resolvemethod, the parameters into Promise instance, further processing.

Here is an example, if the result is not obtained within the specified time, the state will be changed Promise rejectotherwise becomes resolve.

const p = Promise.race([
  fetch('/resource-that-may-take-a-while'),
  new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('request timeout')), 5000)
  })
]);

p
.then(console.log)
.catch(console.error);

 

ORIGINAL http://es6.ruanyifeng.com/#docs/promise

Guess you like

Origin www.cnblogs.com/yangjie-space/p/11616314.html
Recommended