Ruan Yifeng's ES6 --- Promise objects

Original link: http://www.imooc.com/article/20580?block_id=tuijian_wz

Promise meaning
promise is asynchronous programming a solution, more reasonable and more powerful than traditional callback functions and events
. He first proposed by the community and realize, ES6 its standard written language, unified usage, the promise to provide original object.
The so-called promise, it simply is a container, which holds the event will end sometime in the future (usually an asynchronous operation) result, grammatically speaking, promise an object, you can get messages from the asynchronous operation of it, promise provides a uniform API, a variety of asynchronous operations can be handled the same way.
Features promise object
(1) the state of objects from external influences, promise object represents an asynchronous operation, there are three states, pending (in progress), fulfilled (been successful), rejected (failed). Only results of asynchronous operations, you can decide what kind of current state, no other operations can not change this state, which is the promise of the origin of the name "commitment if";
(2) Once the status change will not change any time can get this result, the state's promise to change the subject, there are only two possibilities: from pending becomes fulfilled, from pending changes to rejected. Then you called resolved (finalized). If the change has occurred, you add objects to promise callback function will immediately get this result, which is an event (event) is completely different, the characteristics of the event is: If you missed it, go listen is not the result of of.

With Promise object, the process may be asynchronous operation to synchronous operation expressed, to avoid deeply nested callback function. Further, Promise object provides a unified interface, so that the control of asynchronous operations easier.

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

A usage
promise object is a constructor to generate promise instance;
create an object instance promise

var promise = new Promise( function( resolve, reject) { //some code  if(//异步操作成功){ resolve(value); }else{ reject(error); } });

Promise constructor accepts a function as a parameter, the function of the two parameters are the resolve and reject, they are two functions provided by the Javascript engine, do not have to deploy.

Function is to resolve the role of the state of the object from promise "pending" becomes '' 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 promise instance generation, you can specify a callback function resolved state by state and then rejected Methods

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

acceptable method may then even a callback function as a parameter, a first state of the callback function is called when the object becomes resolved promise, the second callback is called when the object becomes Rejected promise state, wherein the second function is optional, not required to provide these two functions take the object value promise came as a parameter;
simple example of promise object

function timeOut (ms) { return new Promise(function(resolve,reject) { return setTimeout(resolve,ms,"done"); }) } timeOut(3000).then( function(value){ console.log(value); })

timeOut method returns a promise instance, represents the result will occur after a period of time, over a specified period of time (ms) after the state promise instance becomes resolved, it will trigger a callback function then bound method

Promise will be executed immediately after the new

let promise = new Promise(function(resolve, reject) { console.log('Promise'); resolve(); }); promise.then(function() { console.log('resolved.'); }); console.log('Hi!'); // Promise // Hi! // resolved

Promise performed immediately after the new, so the first output is the Promise. Then, then the method specified callback function, the script will be executed in the current sync all tasks executed, it resolved the final output.

Asynchronous Load picture your example

function loadImageAsync (url) { return new Promise( function( resolve, reject){ var image = new Image(); image .onoad = function(){ resolve(image); }; image.onerror = function () { reject(new Error("could not load image at "+ url) ); }; image.src =url; }); } loadImageAsync(url).then( function (value) { console.log(value); })

Promise wraps using asynchronous operation to load a picture. If the load is successful, it calls the resolve method, otherwise it calls reject method.

Examples promise ajax operation object implementation

var getJSON = function (url) { var promise = new Promise( function(resolve,reject ) { var XHR = new XMLHttpRequest(); XHR.open("GET",url); XHR.onreadystatechange = function () { if (this.readyState !==4) {return;} if(this.status == 200) { resolve(this.response); } else{ reject(new Error(this.statusText) ); } }; XHR.responseType = "json"; XHR.setRequestHeader("Accept","application/json"); XHR.send(); }); return promise; }; getJSON("posts.json").then(function(json){ console.log("Contents : "+json ); }, function(error) { console.log("出错了", error); }) ;

getJSON XMLHTTPRequest is encapsulation of an object, for issuing a request for HTTP JSON data, and returns a promise object to be noted that, when the internal getJSON, function and resolve reject function calls, has parameters;
if the resolve call and reject function with a function parameter, then their argument will be passed to the callback function, parameter reject function typically an instance of the error object represents an error thrown, the function parameters resolve addition to the normal value, can also be another example of promise;

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

p1 and p2 are examples Promise, but will resolve method p2 p1 as a parameter, i.e. a result of the asynchronous operation is another return asynchronous operation.
At this time will be transferred to the state p1 p2, that is to say, p1 state determines the state of p2. If the state p1 is pending, then the state will wait for the callback function p2 p1 change; if p1 state has been resolved or rejected, then p2 callback function will be executed immediately.
Note that the call does not resolve or reject or terminate execution parameters of the function of Promise.

new Promise((resolve, reject) => { resolve(1); console.log(2); }).then(r => { console.log(r); }); // 2 // 1

After the call to resolve (1), the latter console.log (2) would be executed and will be printed first. This is because the Promise is resolved immediately at the end of the current round of the event loop execution, always in sync task late round cycle.

In general, subsequent calls to resolve or reject, Promise mission is complete, subsequent operations should be placed inside then the method should not be directly written on the back of resolve or reject. Therefore, the best in front of them plus the return statement, so there would be no accident.

new Promise((resolve, reject) => { return resolve(1); // 后面的语句不会执行 console.log(2); })

Promise.prototype.then ()
Promise example method then having, say, then the method defined in the prototype object Promise.prototype. His role is to add a callback function when the state is changed to Promise instance. As mentioned above, the first parameter is the callback method then resolved state, the second parameter is a callback function rejected state.
thenf method returns a new instance of Promise (Promise that not the original instance), can be written using the chain, i.e., the method then back again then calls another method

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

In turn specifies two callback functions, the first one back after completion will function returns the result as a parameter passed in the second callback function.
The use of chain then, you can specify a set of callback functions in the order called. Then before a callback function, it is possible to return a promise or objects (that is asynchronous operation), then after a callback function, it will wait for the promise of the object state changes, will be called.

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

The above first method specified callback function then returns the object is another promise, this time, then the second method specified callback function, it will wait for the new object state changes Promise. If you become resolved, it calls funA, if the state becomes rejected, it calls funB. Arrows to function code more concise:

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


Author: startitunderground
link: http: //www.imooc.com/article/20580 block_id = tuijian_wz?
Source: Mu class network

Guess you like

Origin www.cnblogs.com/danchaofan123/p/12014000.html