The use of promise

Source: Internet
Author: User
Preface

have been trying to write an article on promise to sum up before the promise knowledge points, take advantage of the work of leisure, to make a summary. PS: This article is suitable for a certain JavaScript basic children's shoes reading. What is Promise

When it comes to JavaScript asynchronous processing, I think most people would think of using a callback function:

1 2 3 4 5 6 7
Example: Asynchronous processing with callback functions Http.get ('/v1/get ', function (error, data) {if (error) {//Error processing}//successful processing})

Like the above. Asynchronous processing based on callback functions if the uniform parameters use the rules, the wording will be very clear. However, this is only a coding protocol, even if the use of different writing will not error.

The promise is to standardize the similar asynchronous processing objects and processing rules, and to write according to the unified interface, and to adopt the prescribed method will be the error. Let's look at an example:

1 2 3 4 5 6
var promise = Http.get ('/v1/get '); Promise.then (function (Result) {//Processing on success}). catch (Process of function (Error) {//Error processing})

As you can see, when using promise for a one-step process, we have to write the processing code in accordance with the method specified by the interface. That is, methods other than the Promise object-defined method (here's then or catch) are not available, rather than being able to freely define the parameters of the callback function as the callback function does, but must strictly follow a fixed, unified programming approach to writing code. In this way, based on the Promise unified interface approach, can form an interface based on a variety of asynchronous processing mode.

But this is not a good reason to use promise, Promise provides a unified interface for asynchronous operations, allowing the code to not fall into the dead end of a callback nesting, which is powerful in its chained calls (which are mentioned later in the article). Basic Usage

Syntax for promise:

1 2 3 4
New Promise (function (resolve, reject) {//Pending asynchronous logic//processing end, invoke resolve or Reject method})

Creating a new promise is simple and requires only a new promise object. So promise is essentially a function that takes a function as an argument and returns a Promise object, which provides the basis for a chained call.

In fact, the mission of the Promise function is to build an instance of it, and to help us manage these instances. These instances have the following three states: pending: Initial state, bit fulfillment or rejection fulfilled: means the operation completed successfully rejected: means the operation failed

The Promise object of the pending state may return a value in the fulfilled state, or it may be rejected (reject) for some reason (exception information). When either of these cases occurs, the then method binding of the Promise object (handlers) is invoked, and the then method specifies the callback function for the Resolve method and the Reject method, respectively

A picture wins thousand words:

A simple example:

1 2 3 4 5 6 7 8 9 10 11 12-13
var promise = new Promise (function (resolve, reject) {if (/* Asynchronous operation succeeded *) {resolve (value);} else {reject (error);}); Promise.then (function (value) {//If the Resolve method is invoked, execute this function}, function (value) {//If the Reject method is invoked, execute this function});

The above code clearly shows the mechanism for the promise object to run. Let's look at an example below:

 
1 2 3 4 5 6 7 8 9-A-K (+)
var Getjson = function (URL) {var promise = new Promise (function (resolve, reject) {var client = new XMLHttpRequest (); CLI Ent.open ("get", url); Client.onreadystatechange = handler; Client.responsetype = "JSON"; Client.setrequestheader ("Accept", "Application/json"); Client.send (); function handler () {if (This.status = =) {resolve (this.response);} else {Reject (new Error (This.statustext));} }; }); return promise; }; Getjson ("/posts.json"). Then (function (JSON) {Console.log (' Contents: ' + JSON);}, function (Error) {Console.error (') ', error); });

In the code above, the Resolve method and the Reject method call have parameters. Their arguments are passed to the callback function. The parameters of the Reject method are usually instances of the error object, and the Resolve method's arguments, in addition to the normal values, may be another promise instance, such as the following.

1 2 3 4 5 6 7 8
var p1 = new Promise (function (resolve, reject) {//... some code}); var P2 = new Promise (function (resolve, reject) {//... some code resolve (p1);})

In the code above, both P1 and P2 are instances of promise, but P2 resolve method takes P1 as an argument, at which point the P1 state is passed to P2. If the P1 state is pending when invoked, then the P2 callback function waits for the P1 state to change, and if the P1 state is already fulfilled or rejected, then the P2 callback function is executed immediately. chain operation of Promise

As mentioned earlier, the Promise.prototype.then method returns a new Promise object, so you can use a chained style.

1 2 3 4 5
Getjson ("/visa.json"). Then (function (JSON) {return json.name;}). Then (function (name) {//proceed});

The code above uses the then method, which in turn specifies two callback functions. When the first callback function completes, the return result is passed as an argument and the second callback function is transmitted.

If the previous callback function returns a Promise object, the latter callback function waits for the Promise object to have a running result before it is called further.

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.