JS----Promise (i)

Source: Internet
Author: User

Data Link: http://liubin.org/promises-book/#what-is-promise 1. What is PromisePromise is a component that abstracts objects asynchronously and handles various operations on them. 2. What is the form of expression? callback function: Getasync ("FileA.txt", function (error, result) {if (error) {////failed to handle throw error;}//successful processing}); Asynchronous processing using promise: var promise = Getasyncpromise ("FileA.txt"); Promise.then (function (Result) {//Get processing of file content success}). catch (function (error) {//Get processing of file content failure}); Compared to asynchronous callback functions: When using promise for one-step processing, we must write the processing code according to the method specified by the interface. In other words, methods other than those specified by the Promise object (then or catch) are not available, rather than being able to define the parameters of the callback function in the same way as the callback function, and must strictly follow a fixed, unified programming method to write code. 3. How do I use it? There are currently roughly three types of the following. Constructorpromise is similar to  xmlhttprequest, from constructor  Promise  to create a new Promise object as an interface. To create a Promise object, you can instantiate it by using new to invoke the promise constructor. var promise = new Promise (function (resolve, reject) {//asynchronous processing//processing ends, call resolve or Reject}); Instance method for Promi generated by new The Promise.then ()   instance method can be used by the SE object in order to set its value in  resolve (success)/ reject (failed) call callback function. Promise.then (onfulfilled, onrejected) Resolve (successful) onfulfilled  will be called when reject (failed) onrejected  will be called onfulfilled, onrejected  two are optional parameters. promise.then  can be used when both success and failure are successful. In addition, you can use  promise.then (undefined, onrejected)   This method only when you want to handle exceptions, only specify the callback function for reject. But in this case  promise.catch (onrejected)   should be a better choice. Promise.catch (onrejected) static method like  Promise  global objects also have some static methods. including  promise.all ()   and  promise.resolve ()  , etc., are mainly auxiliary methods for Promise operation.  function asyncfunction () {return new Promise (function (resolve, reject) {setTimeout (function () {Resolve (' Async Hello world ');}, 16);}); Asyncfunction (). Then (function (Value) {Console.log (value);//= ' Async Hello world '). catch (function (error) {Console.log (error);}); Asyncfunction This function returns the Promise object, for this promise object, we call its then method to set the resolve callback function, the Catch method to set the callback function when the error occurs.   The Promise object will be resolve at 16ms after settimeout, and then the callback function will be called and output ' Async Hello world '.   Status of 4.promiseThe Promise object instantiated with new Promise has the following three states. "Has-resolution"-fulfilledresolve (Success). The onfulfilled "Has-rejection"-rejectedreject (failed) is called at this time. The onrejecte "unresolved" is called-pending is neither resolve nor reject state. That is, the Promise object has just been created after the initialization state and so on the above three states of the reading method, where the left side is defined in the ES6 Promises specification, and the right side is the term described in the promises/a+ state 5. Code writingfunction GetURL (URL) {return new Promise (function (resolve, reject) {var req = new XMLHttpRequest (); Req.open (' GET ', URL , true); Req.onload = function () {if (req.status = = =) {resolve (req.responsetext);} else {Reject (new Error (Req.statustext)) ; } }; Req.onerror = function () {Reject (new Error (Req.statustext));}; Req.send (); }); }//Run the sample var URL = "Http://httpbin.org/get"; GetURL (URL). Then (function onfulfilled (value) {Console.log (value);}). catch (function onrejected (error) {Console.error (error);}); GetURL calls resolve only if the result status is 200 through XHR-that is, when the data succeeds, the Reject method is called when the other condition (failed) is obtained. Resolve (Req.responsetext) added parameters to the contents of response. The parameters of the Resolve method do not have a specific rule, basically put the parameters to be passed to the callback function in it. (then the method can receive this parameter value) 6.promise.resolveIn general we will use new Promise () to create Promise objects, but we can use other methods as well. Here promise.resolve is used for example: New Promise (function (Resolve) {resolve (42);}); In this code the resolve (42); Causes the Promise object to immediately enter the deterministic (i.e. resolved) state and pass 42 to the onfulfilled function specified in subsequent then.   When using Promise.resolve (value)   and other methods, if the Promise object can immediately enter the resolve state, then you do not think that  .then  The method that is specified in the inside is synchronous call? In fact, the method call specified in, .then  is asynchronous. var promise = new Promise (function (resolve) {Console.log ("inner Promise");//1 Resolve (42);}); Promise.then (function (value) {Console.log (value);//3}); Console.log ("outer promise"); 2 since JavaScript code executes from top to bottom of the file, the first <1> executes, then resolve (42); Be executed. At this time the Promise object has become a deterministic state, fulfilled is set to 42.   The following code Promise.then registered <3> This callback function, which is the focus of this column.   Because the Promise object is already deterministic in the execution of Promise.then, it makes sense to invoke synchronous calls to the callback function from the program. However, even if the Promise object is already a deterministic state when calling Promise.then to register a callback function, promise will invoke the callback function asynchronously, which is a prescribed guideline in promise design.   So <2> will be called first, and the callback function <3> will be called at the end.   Since promise guarantees that each invocation is performed asynchronously, we do not need to call setTimeout in the actual encoding to implement the asynchronousCall.           

JS----Promise (i)

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.