The promise of the big liar JS artifact

Source: Internet
Author: User

The previous period of work, because the project to the front-end implementation of storage, so the use of Websql, and Websql API involves a lot of asynchronous problems, if the way to take the callback function, the code is not elegant, and is not conducive to understanding, so they found the promise, After the use of some of their own understanding and experience, to share with you in this article.

What is promise?

Promise Chinese interpretation for "oath", "commitment" means, according to its transliteration, that is "Prometheus", this goods is very powerful Ah, in Greek mythology, is one of the most intelligent gods, the earliest Titan giant God descendants, the name has "foresight" (forethought) meaning.

And JS in the promise, in fact, is a ES6 to provide an object, it acts as a "prophet" such a role, it is used to pass the asynchronous operation of the message, representing a future will know the outcome of the event, and this event provides a unified API for further processing, This class is currently supported in Chrome32, OPERA19, and Firefox29 versions.

Next talk about promise norms, everyone should be unfamiliar, because this specification has been out for a long time, at present in Chrome32, Opera19, Firefox29 above the version has been supported promise, promise the main contents of the specification are as follows:

    • There are three states of the Promise object: Pending (in progress), resolved (completed), rejected (failed), these three states can only be transferred from Pending to rejected or Pending to rejected, and cannot be reversed. And once the transition is complete, the state is solidified and can no longer be changed. Only the result of an asynchronous operation can determine which state is currently, and no other operation can change that state, which is not the same as deferred.
    • The only interface required by the Promise mode is to call the then method, which can be used to register a callback function that is called when promise completes or fails, then the method accepts two arguments, the first argument is a successful callback, Called when the promise is converted from pending to resolved state, and the other is a failure callback when the promise is converted from pending to rejected state.
What good is promise?

What good is promise to say so much? What can be convenient for our work? Not much to say, is the mule is horse-drawn out to walk, we first new one to play:

var New Promise (function(resolve, Reject) {    // setTimeout simulates asynchronous Operation    SetTimeout ( function () {        console.log (' first promise execution completed ');        Resolve (' first promise ');     (a);});

The above code can be seen, new a Promise object, to pass in a function, and this function generally has two parameters, one is resolve, the other is reject, these two parameters are not necessarily, but you have to use the one must be passed, so two are written on the good, These two parameters actually represent the callback function after the successful execution of the asynchronous operation and the failed execution of the asynchronous operation. And the above code means to imitate an asynchronous operation with SetTimeout, after 2 seconds, in the console print "First promise execution Complete", and then call the Resolve method, with a parameter: "The first Promise", run the code, will directly output " The first promise executes ", although we are just new with a promise object, but the function is executed immediately when the argument is passed in, so the direct output, in order to prevent this, we have this code wrapped in a function:

function test1 () {  varnew Promise (function(resolve, Reject) {    //  do some asynchronous operations    setTimeout (function() {        console.log (' first promise execution complete ' ) );        Resolve (' first promise ');     (a);    })    ; return p;}

As above, finally return a Promise object, the next play comes, the Promise object's then method to appear, it can be used to register when promise completed or failed to invoke the callback function, we then continue to write the above code:

Test1 (). Then (function(val) {    Console.log (val))    ; // subsequent operations     })

Execute this code, after two seconds, the page output "first promise execution Complete", followed by the output "first promise". Here, the wit you have seen, this then is not the asynchronous processing completed, will pass over the data to take, and then follow up, is to act as a callback function, feel this promise is not a big deal of place Ah, but is the original callback to separate out the wording, After the asynchronous operation is executed, the callback function is executed in the form of chained invocation, in fact, this kind of chain call is necessary in some more complicated pages, because if the callback function is relatively small, if it is a bit more and must pay attention to the order of execution, the callback function begins to nest, The nausea of the code is simply intolerable. And the appearance of promise is to solve this problem.

Promise provides an elegant solution, with the main usage being to encapsulate individual asynchronous operations into many promise, while a promise handles only one asynchronous logic. Finally, each promise is concatenated with chained invocation notation, so that if the relationship between asynchronous logic is heavy, you do not need to nest layers, just encapsulate each asynchronous logic into a promise chain call.

Basic API for Promise

Say not much, first with Console.dir (Promise) print out to see:

It can be seen that there are several main ways to do this:

    1. Resolve: This method can change the state of the Promise object to success, while passing a parameter for subsequent successful operations.
    2. Reject: This method changes the state of the Promise object to failure while passing the wrong information to the subsequent error-handling operation.
    3. Then: All Promise object instances have a then method, which is used to interact with this Promise, then the method mainly passed two methods as parameters, a resolve function, a reject function, chained call, on When a Promise object becomes resolved, call the Resolve method in then, otherwise call the Reject method, and the then method calls the Resolve () function by default.
    4. Catch: This method is a simple notation of the onrejected function in the then (onfulfilled, onrejected) method, that is, it can also be written as then, but it is easier to understand when catching an exception.
    5. All: The method can receive an array of Promise objects as a parameter, which is returned when all Promise objects inside the array become resolve. It's all done before it goes down, for example:
 var  p1 = new  Promise (function   (resolve) {setTimeout ( function   () {resolve (" P1 " 2000 var  p2 = new  Promise (function   (resolve) {setTimeout (     function   () {Resolve ( "P2"  2000 function   ( Result) {Console.log (result);});  

6. Race: Racing, like the All method, it also receives an array, but the method returns whenever the state of the Promise object in the array changes (either resolve or reject). is to execute it as soon as one of the executions is done.

Chained invocation of Promise

Then the chain call is the meaning of promise, and to implement chained invocation, then the Resolve method how to return is critical. The then method typically passes two parameters, a resolve function, and a reject function. Reject is not discussed for the time being, it is the function that runs when the error occurs. The Resolve function must return a value in order to make the chained call go down, and this value returns what is very much fastidious.

    • In the then resolve method, return a new Promise object with the following code:

functiontest1 () {varp =NewPromise (function(Resolve, reject) {//do some asynchronous operationsSetTimeout (function() {Console.log (' First promise performed '); Resolve (' The value of the first promise '); }, 2000);    }); returnp;} Test1 (). Then (function(val) {Console.log (' Go to the first then ');    Console.log (Val); varP1 =NewPromise (function(Resolve, Reject) {SetTimeout (function() {Console.log (' First then execution done '); Resolve (' The value of the second promise '); }, 2000); })    returnP1; }). Then (function(val) {Console.log (' Go to the second then '); Console.log (val);})

The printing results are as follows:

The above example prints out the corresponding contents in sequence by chaining calls. Then you can use chained calls because you always return a Promise object each time you execute the method, and then the Resolve method in the next then executes when the previous then finishes processing. And then returning a new promise and then calling it is the logic in the new promise. In addition, the return value in the then onfulfilled function can be used as a parameter for subsequent operations.

    • Return a value in the then resolve method, as in the following code:

functiontest1 () {varp =NewPromise (function(Resolve, reject) {//do some asynchronous operationsSetTimeout (function() {Console.log (' First promise performed '); Resolve (' The value of the first promise '); }, 2000);    }); returnp;} Test1 (). Then (function(val) {Console.log (' Go to the first then ');      Console.log (Val); SetTimeout (function() {Console.log (' First then execution done '); }, 2000); return' The value of the second promise '; }). Then (function(val) {Console.log (' Go to the second then '); Console.log (val);})

The printing results are as follows:

As can be seen, the first then in the resolve has not finished, entered the second then, did not wait, because the first then returned a string, rather than the Promise object, the returned value will be passed to the next resolve method parameter.

Summarize

The above is the basic concept and usage of ES6 Promise, Promise is still very good, if you are still using callback mode, I strongly recommend that you switch to Promise, so that your code will become less, more elegant, and easier to understand, so that you do not wait for the development of the end, The people who read your code secretly scold you behind their backs. This article I myself understand the combination of some of the information on the Internet, I hope you after reading to help you, there are shortcomings welcome to correct, thank you ~

The promise of the big liar JS artifact

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.