The study of ES6 's Promise

Source: Internet
Author: User

Meaning of the 1.Promise:

Promise is a solution for asynchronous programming that is more logical and powerful than traditional solutions-callback functions and events. It was first proposed and implemented by the community, ES6 wrote it into the language standard, unified the usage, the native provided the Promise object.

The so-called Promise simple is a container that holds the result of an event (usually an asynchronous operation) that will end in a future. Syntactically speaking, promise is an object from which you can get the message of an asynchronous operation. Promise provides a unified API, and various asynchronous operations can be handled in the same way.

PromiseThe object has the following two characteristics.

(1) The state of the object is unaffected by the outside world. PromiseThe object represents an asynchronous operation with three states: ( Pending in progress), Resolved (completed, also called fulfilled), and Rejected (failed). Only the result of an asynchronous operation can determine which state is currently, and no other operation will change that state. This is also the origin of the Promise name, its English meaning is "commitment", that other means can not be changed.

(2) Once the state changes, it will not change, and can get this result at any time. PromiseThere are only two possible changes in the state of an object: from change to Pending Resolved and from Pending Rejected . As long as these two situations occur, the state is solidified and will not change, and will keep the result. Even if the change has occurred, you Promise can add the callback function to the object, and you will get the result immediately. This is quite different from the event, which is characterized by the event that if you miss it and then listen to it, you won't get the result.

Basic implementation of 2.Promise

varPromisecount=0;functiontestpromise () {varThispromisecount = + +Promisecount; varp=NewPromise (function(Resolve, reject) {//Resolve successful reject failureSetTimeout (function(){            if(thispromisecount<2) {resolve (Thispromisecount); }Else{Reject (Thispromisecount)}},math.random ()*2000+1000);    }); P.then (function(val) {Console.log ("End:" +val+ "promise is satisfied (asynchronous code end)"); return' Success '; },function(Error) {Console.error (' ERROR: ' +error+ ' promise failed (async code end) "); return' Error '}). Then (function(val) {Console.log (val); })} testpromise ();

Above is a basic implementation of a simple promise. The promise constructor takes a function as a parameter, and the two parameters of the function are resolve and reject. Resolve represents a successful post-execution method, reject is a method that executes after a failure, and new promise generates an instance that, after the instance is generated, can use the then method to specify the callback function for the resolved state and the Reject State, respectively. Then there are two callback functions, the first one is a successful callback, the second is a failed callback.

3. Promise.prototype.then

The then method returns a new promise instance (note that it is not the original promise instance). You can therefore use chained notation, which is followed by another then method. The first parameter is the callback function for resolved, the second is optional, and the rejected callback function

varGetjson =function(URL) {varPromise =NewPromise (function(Resolve, reject) {varClient =NewXMLHttpRequest (); Client.open ("GET", URL); Client.onreadystatechange=handler; Client.responsetype= "JSON"; Client.setrequestheader ("Accept", "Application/json");        Client.send (); functionhandler () {if( This. readyState!== 4) {                return; }            if( This. Status = = 200) {Resolve ( This. Response); } Else{Reject (NewError ( This. statustext));    }        };    }); returnpromise;}; Getjson ("/post/1.json"). Then (function(POST) {returnGetjson (Post.commenturl);}). Then (functionFunca (comments) {Console.log ("Resolved:", comments);},functionFUNCB (Err) {Console.log ("Rejected:", err);});

The preceding code uses the then method, which in turn specifies two callback functions. When the first callback function finishes, the returned result is passed as an argument to the second callback function.

4. Promise.prototype.all

The Promise.all method is used to wrap multiple Promise instances into a new Promise instance.
An array may not be an array, but must have an iterator interface, and each member returned is a promise instance.
(1) Only the state of Prolist becomes the fulfilled,p state will become fulfilled, when the return value of prolist constitutes an array, passed to P's callback function.
(2) As long as there is a rejected,p state in the prolist becomes rejected, at this time the first instance of the Reject return value, will be passed to the callback function p.

Ar arr=[1,2,3];functionGetpro (a) {return NewPromise (function(resolve,reject) {if(a>2) {reject (a); } resolve (a)})}varProlist=arr.map (function(ID) {returnGetpro (ID);}); Promise.all (prolist). Then (function(val) {Console.log (val);}).Catch(function(e) {Console.log (' ERROR: ' +e);});

The above example is a simple promise.all implementation, prolist inside of the three promise instances, if three all return resolve, then will go the first then inside the method, if there is a return reject, then long will go to the last catch method;

4.promise.prototype.race

Promise.race (), the parameter is the same as the Promise.all parameter,
In the example below, as long as there is an instance in P1 and P2 to change the state, P3 's state changes. The return value of the first changed promise instance is passed to the P3 callback function. P3 's callback is to see the first change in state P1 or P2 promise inside the function resolve or reject,
If the first change of state of the promise is reject, then the catch callback will go, and vice versa will go then the first callback method;

varp1=NewPromise (function(resolve,reject) {setTimeout (function() {Console.log (P1); Resolve (' P1:=>success '); },math.random ()*1000)});varP2=NewPromise (function(resolve,reject) {setTimeout (function() {console.log (P2); Reject (' P2:=>error '); },math.random ()*1000)});varP3=promise.race ([P1,P2]). Then (function(data) {Console.log (p3); Console.log (data);}).Catch(function(Error) {Console.log (p3); Console.log (Error);});

5.promise.prototype.catch

Catch catch errors catch all errors in all then methods above the catch;

/** * Due to not specifying the use of the Try...catch statement, it bubbles to the outermost layer and becomes an uncaught error. Caught with catch, this error is thrown outside the body of the promise function. * @type {Promise}*/varPromise =NewPromise (function(Resolve, Reject) {Resolve ("OK"); SetTimeout (function () {        Throw NewError (' Test ')    }, 0)});p Romise.then (function(value) {Console.log (value)}).Catch(function(e) {console.log (e);});/** * It is important to note that the catch method returns a Promise object, so you can then call the then method later. * @returns {Promise}*/varSomeasyncthing =function () {    return NewPromise (function(Resolve, reject) {//the following line will cause an error because X is not declaredResolve (x + 2); });}; Someasyncthing ().Catch(function(Error) {Console.log (' Oh no ', error);}). Then (function() {Console.log (' Carry On ');});

6.promise.prototype.resolve and Promis.prototype.reject;

Sometimes need to convert the existing object to Promise object, Promise.resolve method to play this role, Promise.resolve () has the following three kinds of use of the plot, Promise.reject and promise.resolve using the same method;

/** * For example below P1 equivalent to P2 * @type {promise.<string>}*/varP1=promise.resolve (' foo '));varP2=NewPromise (function(Resolve,reject) {Resolve (' Foo ');}); P1.then (function(data) {Console.log (data);//Foo});/** * When there are no parameters, the return function does not have parameters * @type {promise.<string>}*/varp3=promise.resolve ();p 3.then (function() {Console.log (' Resolve no Parameters! ');});/** * When an object has then this parameter; * @type {promise.<string>}*/varenable={then:function(Resolve,reject) {Resolve (50); }};varp4=promise.resolve (Enable);p 4.then (function(s) {console.log (s);});

Reference URL: http://es6.ruanyifeng.com/#docs/promise

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

The study of ES6 's Promise

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.