Promise object of ECMASCRIPT6

Source: Internet
Author: User

1. Concept

The Promise object is used for asynchronous (Asynchronouss) computations, and a Promise object represents an operation that is not yet completed, but is expected to complete.

2. Reason for the occurrence:

1) If you need to send multiple requests through Ajax, and each request relies on the result returned by the last request as a parameter to continue the next request, then you need to write this code:

  

In the above example, assuming that request C needs to rely on the data returned by B, then C needs to be placed in the success function of B. Similarly, a needs to rely on the data returned by B, then a also needs to be placed in the success function of B. Assuming that there are many requests, before the request is a mutual dependency, then we need to nest a lot of layers, so that the code is very poor readability, not intuitive, debugging is not convenient, maintenance is not convenient.

2) If the request C needs to rely on the results of a and B, and the A and a, a and a are independent of each other, without dependencies, then if you use the implementation above, A (b) needs to rely on B (a) to complete before it can be called, which will require a longer wait time.

So, in order to deal with this kind of callback function layer nesting problem (also called "Callback Hell"), so promise appeared.

3. Syntax

New Promise (function (resolve,reject) {

Operation...

});

The Promise object is a global object, and you can also understand it as a class that uses the new keyword when creating an promise instance. Of these, resolve and reject two parameters are function objects. Resolve is a scenario used to handle successful execution, and reject is used in scenarios where the execution fails, and once the operation is complete, the two functions can be called. The specific invocation is to use the then () method to bind the handler after the operation, using the following explanation.

4. Parsing

Three states of the Promise object:

1) Pending: When you have just created an promise instance, it represents the initialization state

2) When the Fulfilled:resolve method is called, it indicates that the operation was successful

3) When the Rejected:reject method is called, indicates that the operation failed

The Promise object of the pending state can be converted to a fulfilled state with a success value, or to a rejected state with a failed message. When the state transitions, the Promise.then bound method (the function handle) is called. (When binding a method, if the Promise object is already in the fulfilled or rejected state, the corresponding method will be called immediately, so there is no race condition between the completion of the asynchronous operation and its binding method.) )

  

(Image source: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise)

5. Properties

Promise.length: Length property with a value of 1 (number of construction parameters)

Promise. Prototype of the Prototype:promise constructor

6. Methods

1) Promise.then () method: Used to bind the handler after the processing operation.

2) Promise.catch () method: Used to handle the page after the operation exception.

3) then () and catch () examples of combined use:

4) layer depends on promise processing:

Code:

1 Let Pro = new Promise (function (resolve,reject) {2 if (true) {3 Resolve (' Operation succeeded ');//The Resolve function returns a value at this time4                 }5 else{6 reject (' operation failed ');7                 }8             });9 Ten Pro.then (Requesta) One . Then (REQUESTB) A . Then (REQUESTC) - . catch (Requesterror); -  the function Requesta (res) { - Console.log (res);//output resolve return value--operation succeeded - Console.log ("Request a Success"); - return "Request A, the next step is b you"; +             } -  + function Requestb (res) { A Console.log ("The previous step is" +res); at Console.log ("Request B Success"); - return "Request B, the next step is C you"; -             } -  - function REQUESTC (res) { - Console.log ("The previous step is" +res); in Console.log ("Request C Success"); -             } to  + function Requesterror () { - Console.log ("request Failed"); the}
View Code

Results:

Parse: In the above example: first create an instance, also declared 4 functions, of which three are respectively represented by the request a, B, C, and then method, in order of invocation, it is very intuitive to complete the binding of three operations. Also, if request B relies on the result of request a, you can pass the required data as a parameter to the next request using the return statement in the program requesting a.

(image example from public number: "Web front-end tutorial")

5) Promise.all () method: Accepts an array as an argument, the element of the array is an Promise instance object, and Promise.all () returns when the state of the instance object in the argument is fulfilled.

Resolution: Pro2 first into the success of fulfilled state, is promise.all () can not enter then method, until after 5s, Pro1 into a successful fulfilled state, Promise.all () before entering then method, output results: [" Instance 1 operation succeeded "," Instance 2 succeeded "]

6) Promise.race (): Accepts an array as an argument, the element of the array is an Promise instance object, and when the instance object in the argument has a state (whether fulfilled or rejected), Promise.race () Will enter the then method.

7. Prototypes

Property:

Promise.prototype.constructor: Returns the function that created the instance prototype. The default is the Promise function

Method:

Promise.prototype.catch (onrejected): Adds a negative (rejection) callback to the current Promise, returning a new Promise. If this callback is called, the new promise will be resolve with its return value, or if the current promise enters the fulfilled state, the positive result of the current promise as a positive result of the new promise.

Promise.prototype.then (onfulfilled, onrejected): Adds a positive and negative callback to the current Promise, returns a new Promise, which is resolve with the return value of the callback.

8. Example

Examples of reference:

1 <DivID= "Log"></Div>2     <Script>3         'Use Strict';4         varPromisecount= 0;5         functiontestpromise () {6             varThispromisecount= ++Promisecount;7             varLog=document.getElementById ('Log');8 log.insertadjacenthtml ('BeforeEnd', Thispromisecount+ ') Start (Sync code start) <br/>');9             //we create a new promise: Then use the ' result ' string to complete the promise (after 3 seconds)Ten             varP1= NewPromise (function(Resolve, reject) { One                 //completion function with the ability to complete (resolve) or reject (reject) promise is executed A log.insertadjacenthtml ('BeforeEnd', Thispromisecount+ ') promise Start (Async code start) <br/>'); -  -                 //This is just an example of creating an asynchronous completion the Window.settimeout (function () { -                    //We meet (fullfil) this promise! - Resolve (Thispromisecount) - }, Math.random ()*  - +  +); +             }); -             //define what should be done when promise is satisfied + P1.then (function(val) { A                 //output A section of information and a value at log.insertadjacenthtml ('BeforeEnd', Val+ ') Promise is satisfied (Async code end) <br/>'); -             }); -  - log.insertadjacenthtml ('BeforeEnd', Thispromisecount+ ') established the Promise (synchronous code end) <br/><br/>'); -         } - testpromise (); in testpromise (); - testpromise ();

Results:

Another good example:

Https://github.com/mdn/promises-test/blob/gh-pages/index.html

9. Summary

Promise is an object that allows developers to handle asynchronous operations more rationally and more appropriately.

10. References

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

Https://developer.mozilla.org/zh-CN/docs/Web/API/Element/insertAdjacentHTML

11. The next arrangement

Ajax Source Code Application

Combining promise and Ajax source code application

Promise object of ECMASCRIPT6

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.