Misunderstanding and practice of promise/a

Source: Internet
Author: User
Tags json log

What is promise

Promise is a more elegant pattern of writing asynchronous code, allowing asynchronous operation code to be written and read like synchronous code, such as the following example of an asynchronous request:

$.get ("/js/script,js", function () {
    //callback to do
})

Can be rewritten as promise mode:

var promise = $.get ("/js/script");

The return value promise represents the final result of the operation. The return value promise can also be passed as a parameter as a "Class I Object" (first-class object). The biggest advantage of this pattern is that it avoids the bad case of a callback function nested callback function in the traditional asynchronous operation code.

If you have any previous knowledge of the Promise model (as you can refer to Infoq's previous article), when it comes to promise, the first thing you'll think of is its then function, which is really important, in the definition of promise schema (Commonjs promises/a) , the then function is so defined:

(original) A promise is defined as an object this has A function as the value for the property Then:then (Fulfilledhandler, error Handler, Progresshandler)

A promise is defined as an object that has a then attribute, and the value of this then property is a function: Then (Fulfilledhandler, ErrorHandler, Progresshandler)

That is to say, every promise result is bound to bring a then function, and through this then function we can add promise transitions to different states (in the definition, promise is only three states, unfulfilled, fulfilled, Failed. This state transition, which is called from unfulfilled to fulfilled, or from unfulfilled to failed, can also monitor the progress event, taking the above code as an example:

var fulfilledhandler = function () {}
var ErrorHandler = function () {}
var progresshandler = function () {}

$ . Get ("/js/script"). Then (Fulfilledhandler, ErrorHandler, 

Progresshandler)

There are some things that are similar to

$.ajax ({
    error:errorhandler,
    success:fulfilledhandler,
    progress:progresshandler
})

This time you will be puzzled, the above two ways do not look almost identical? -but promise's focus is not on the aggregation of the various callback functions mentioned above, but rather on the way in which synchronous functions communicate and communicate with asynchronous functions . It is similar this is also the majority of people's understanding of the promise of the misunderstanding, only stay in the then aggregation (aggregating) function. The same mistakes have even been made in some of the best-known class libraries (e.g., jquery, for example). Here are two common misconceptions to give people a complete understanding of promise.

What is the connection between promise/a mode and sync mode?

Put aside promise, let's look at the two most important features of the sync operation function

can return a value

Ability to throw exceptions

This is actually similar to the composite function in advanced mathematics (function composition): You can pass the return value of a function to another function and pass the return value of another function as an argument to the next function ... As infinite as a "chain" to do so. More importantly, if an exception occurs in one of the links, the exception can be thrown and passed out until caught by catch.

In a traditional asynchronous operation there will no longer be a return value or throw an exception-or you can throw it, but no one can catch it in time. The result is that a series of callbacks must be nested in the callback of the asynchronous operation to prevent unexpected occurrences.

The promise pattern, which is exactly what is intended for these two flaws, enables the function to be combined and thrown (bubbling until captured). A function that conforms to the Promise mode must return a promise, whether it is a fulfilled state or a failed (rejected) state, which we can all consider as a return value in a synchronous operation function:

$.get ("/user/784533")//Promise return
. Then (function Parsehandler (info) {
    var userInfo = Parsedata ( Json.parse (info));
    Return resolve (UserInfo); Promise return
})
. Then (getcreditinfo)//Promise return
. Then (function Successhandler (result) {
    Console.log ("User Credit info:", result);
}, Function ErrorHandler (error) {
    console.error ("Error:", error); c10/>})

In the example above, $.get and Getcreditinfo are both asynchronous operations, but in promise mode, (formally) converted to chain-operated sequential operations

The promise returned by $.get is parsed by Parsehandler, the return value is "passed in" Getcreditinfo, and Getcreditinfo's return value is "passed in" Successhandler.

The reason to put quotes on the incoming word is not to actually pass the promise as a value into the function, but we can simply interpret it as passing in and rewrite it as a synchronous function, so that the function is complex at a glance:

try {
    var info = $.get ("/user/784533");//blocking
    var userInfo = parsedata (Json.parse (info)
    
    ); var resolveresult = Parsedata (userInfo);
    var creditinfo = Getcreditinfo (Resolveresult); Blocking

    console.log ("User Credit info:", result);
} CACTH (e) {
    console.error ("Error:", error);
}

But before the jQuery1.8.0 version, such as jQuery1.5.0 (jquery introduced Promise in the 1.5.0 version, which was corrected at 1.8.0), there were problems that could not catch the exception:

var step1 = function () {
    console.log ("------step1------");
    var d = $. Deferred ();
    D.resolve (' Some data ');
    return D.promise ();
},

step2 = function (str) {
    console.log ("------step2------");
    Console.log ("Step2 recevied:", str);

    var d = $. Deferred ();
    Intentionally throws an exception d.reject in the fulfilled Hanlder
    (the new Error ("This is failing!!!");
    return D.promise ();
},

step3 = function (str) {
    console.log ("------step3------");
    Console.log ("Step3 recevied:", str);

    var d = $. Deferred ();
    D.resolve (str + ' to display ');
    return D.promise ();
},


Completeit = function (str) {
    Console.log ("------complete------");
    Console.log ("[Complete]------>", str);
},

handleerr = function (err) {
    Console.log ("------ Error------");
    Console.log ("[ERROR]------>", err);   

Step1 ().
Then (STEP2).
Then (STEP3).
Then (Completeit, Handleerr);

The results of the above code running in jQuery-1.5.0:

------STEP1------
------STEP2------
step2 recevied:  Some data
------STEP3------
STEP3 Recevied:  Some Data
------complete------
[complete]------> Some Data

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.