$.ajax () A summary of the deferred

Source: Internet
Author: User
Tags first string

The traditional Ajax notation:

$.ajax ({    URL: "1.json",    type: "Get",    success:function (data) {},    error:function () {}});

The new notation after jquery 1.7,

$.ajax ({    URL: "1.json",    type: "Get"    }). Done (function (data) {    }). Fail (function () {    });

I was wondering. $.ajax () returns the XMLHttpRequest object.

We all know that XMLHttpRequest is a core object of Ajax for interacting with servers,
But the XMLHttpRequest object has no Done,fail method at all,
How do you add the method here?
We start with done. Search for done on the official website API.

Find a deferred keyword.

Let's start with the deferred of jquery now.

The

Deferred object was designed by the jquery development team to add jquery to the 1.7 release in order to enhance the callback functionality of jquery.
Defer English meaning is the meaning of delay. So how did he delay it?
first to understand the basics, otherwise you can't say it later.
$. Deferred ([fun])
$. Deferred () returns the Deferred object when there is no parameter; When a
has parameters, it indicates that a delay or asynchronous operation is made on this parameter, and the deferred object is returned.
Done (FN)           Call this method when the delay succeeds
fail (FN)           Call fails when delay fails
then (done,fail)            This is the total write method for done and fail
always (FN)           Regardless of the success or failure of the deferred execution, the FN above may be either a function or multiple comma-separated function functions

Resolve and Reject methods once executed, indicating that the execution begins done,fail , the Then,always method,
Note that the deferred object can hook up multiple done,fail methods at once, executing sequentially in the order in which you distribute them.

Resolve (value)           tells the object to perform a done callback, value is a parameter
reject (value)           tells the object to perform a fail callback, value is a parameter.
Call done callback code:

var DFD = $. Deferred ();d fd.done (function (value) {    alert (value);}); Dfd.resolve ("Execute done callback");

Call the fail callback code:

var DFD = $. Deferred ();d fd.done (function (value) {    alert (value);}); Dfd.reject ("Execute fail callback");

Call then callback code:

var DFD = $. Deferred (); var donefun=function (value) {    alert ("Done:" +value);}; var failfun=function (value) {    alert ("Fail:" +value); Dfd.then (Donefun,failfun);d fd.reject ("Dr. Sisi");

Call the always callback code:

var DFD = $. Deferred (); var donefun = function (value) {    alert ("Done:" + value);}; var failfun = function (value) {    alert ("Fail:" + value);} Dfd.then (Donefun, Failfun). Always (function () {    alert ("If you delay success or failure, I will do everything");}); Dfd.resolve ("I'm going to do it, but this doesn't affect my execution always!");

  

State () returns the current status of the deferred object

1.pending: Operation not completed
2.resolved: Successful operation

3.rejected: Operation failed
Code:

var dfd=$. Deferred ();d fd.done (function () {    console.log ("Done");}); Console.log (Dfd.state ());d fd.resolve (); Console.log (Dfd.state ());

  

Above we said: Resolve means to execute the callback immediately,
So the pop-up in this place is like this

var dfd=$. Deferred ();d fd.progress (function (data) {    alert (data);}). Done (function (data) {    alert ("done:>>>>>" +data);}). Fail (function (data) {    alert ("fail:>>>>" +data);}); function getprocess () {    dfd.notify ("I am the parameter of the progress callback function");    var a=true;    The following is to determine whether to execute done or fail    if (a) {        dfd.resolve ("Doing done ...");    } else{        dfd.reject ("Perform fail ...");}    

  

<input type= "button" value= "OK" onclick= "getprocess ()"/>

According to the above analysis, deferred objects have done such a counter-law,
According to $.ajax (). Done () Guess $.ajax () should return the deferred object?
Let's just say this is the right conclusion.
So Jquey besides $.ajax () has done method, what else has done method.
$.when (d);d is one or more lingering objects, or plain JavaScript objects.
Let's take a look at the parameter as a normal object.

Now talk about the same call with multiple delays

$.when ($.ajax ("1.json"), $.ajax ("2.json"), $.ajax ("3.json")). Done (function (data1, data2,data3) {    Console.log ( DATA1);    Console.log (data2);    Console.log (DATA3);}). Fail (function (data1,data2,data3) {    console.log (data1);    Console.log (data2);    Console.log (DATA3);});

He returned the $.ajax () object back.
This place is using AJAX to do the delay,
So can we use settimeout to simulate the delay

function delay () {    setTimeout (function () {        alert ("executed");    },2000);}        $.when (Delay ()). Done (function () {    alert (' Done ');});

No, this place is the first to execute the done,2s after the execution is settimeout.
Think about it and consider the parameters above.
This place is only a parameter that passes delay () as a parameter to the done callback function. Because it is not a parameter of type deferred.
Because $.ajax () returns the deferred type to use done.
So how do you get delay to return a deferred object to complete our delay simulation?
Now let's think about the first string of code above. Deferred ();
This can return the deferred type.
Rewrite the above code:

var dfd=$. Deferred ();        function delay (DFD) {    var bool=true;    SetTimeout (function () {        alert ("SetTimeout of delay executed!");        if (bool) {            dfd.resolve ("Done");            } else{            dfd.reject ("fail");        }            },2000);    return DFD;} $.when (Delay (DFD)). Done (function (value) {    alert (value);}). Fail (function (value) {    alert (value);});

This time we finally realized the delay, back to the function.
It says done as long as a encounter resolve or fail encountered reject will be executed immediately,
Then we add a line of code at the bottom:
Modify the above code:

var dfd=$. Deferred ();        function delay (DFD) {    var bool=true;    SetTimeout (function () {        console.log ("SetTimeout of delay executed!");        if (bool) {            dfd.resolve ("Done");            } else{            dfd.reject ("fail");        }            },2000);    return DFD;} $.when (Delay (DFD)). Done (function (value) {    console.log ("Done1" +value);            }). Fail (function (value) {    console.log ("Fail1" +value);}); Dfd.resolve ("I'm here to make trouble ...");

  

The order becomes this:

The purpose of our analog delay is obviously compromised.
How to Solve
Change a DFD from a global to a local variable so that no one else can easily change the state.

function delay () {    var dfd=$. Deferred ();        var bool=true;    SetTimeout (function () {        alert ("SetTimeout of delay executed!");        if (bool) {            dfd.resolve ("Done");            } else{            dfd.reject ("fail");        }    },2000);    return DFD;} $.when (Delay ()). Done (function (value) {    alert ("Done1" +value);            }). Fail (function (value) {    alert ("Fail1" +value);});

Or that sentence: done as long as the encounter resolve or fail to encounter reject will be executed immediately
Rewrite the above code:

function delay () {    var dfd=$. Deferred ();        var bool=true;    SetTimeout (function () {        console.log ("SetTimeout of delay executed!");        if (bool) {            dfd.resolve ("Done");            } else{            dfd.reject ("fail");        }    },2000);    return DFD;} var delay2=delay ();d elay2.resolve (), $.when (Delay ()). Done (function (value) {    console.log ("Done1" +value);            }). Fail (function (value) {    console.log ("Fail1" +value);});

  

This time execution becomes so, after 2s:

If our deferred can be tampered with so arbitrarily, then our program is robust,
Is there a way for outsiders to access the deferred object without affecting the invocation of our callback function?
The answer is: Promise ();
Rewrite code:

function delay () {    var dfd=$. Deferred ();        var bool=true;    SetTimeout (function () {        console.log ("SetTimeout of delay executed!");        if (bool) {            dfd.resolve ("Done");            } else{            dfd.reject ("fail");        }    },2000);    return Dfd.promise ();} var delay2=delay ();//delay2.resolve (); $.when (Delay ()). Done (function (value) {    console.log ("Done1" +value);            }). Fail (function (value) {    console.log ("Fail1" +value);});

  

This time you are releasing the note, you will get an error.

Look at the following code error:
$.ajax (). Resolve ();

is not very familiar with the error.
So our $.ajax () is more specifically the Promise object that eventually returns.
$.ajax (), $.when () It's just a way to be blunt.
Since jquery can make a $.ajax (), $.when () interface, we can certainly get a
Such an interface came out.
Back to the top of the string code:
$. Deferred (FN);
We have been using the $ without argument. Deferred ();
What does this fn parameter do? FN is primarily used to deploy asynchronous or deferred operations.

$.delay=$. Deferred (function (DFD) {    setTimeout (function () {        alert ("SetTimeout executed!!!!");        Dfd.resolve ();    },2000);}); $.delay.done (function () {    alert ("Done1");});

Note: The DFD here does not need to be passed when we call, we will pass a deferred object in
This looks like $.ajax () and $.when ().
But not quite the same, $.ajax () and $.when () can pass parameters our $.delay cannot pass parameters, he is not a method, is a promise object.
Continue to refine the above code so that it can pass parameters:

$.delay = function (time) {    return $. Deferred (function (DFD) {        setTimeout (function () {            alert ("SetTimeout executed!!!!");            Dfd.resolve ();}        , time);}    )} $.delay. Done (function () {    alert ("Done1");});

After the code has been optimized, the function is realized;
Here comes the question again. $.delay () is a method that jquery has already defined, and the method we define is the same as jquery.
How about us? $.delay () changed to an ordinary method, not better.

var delay = function (time) {    return $. Deferred (function (DFD) {        setTimeout (function () {            alert ("SetTimeout executed!!!!");            Dfd.resolve ();}        , time);}    )} Delay ((). Done (function () {    alert ("Done1");});

Or something like this:

function delay (time) {    return $. Deferred (function (DFD) {        setTimeout (function () {            alert ("SetTimeout executed!!!!");            Dfd.resolve ();}        , time);}    )} Delay ((). Done (function () {    alert ("Done1");});

It says that by returning the Promise object, the interface is done,
Can you lay out the interface directly on the given function? Here we use the Promise ()
The code is as follows:

var dfd=$. Deferred (), function delay (d,time) {    setTimeout (function () {        alert ("SetTimeout executed!!!");        D.resolve ();    },time);} Dfd.promise (delay);d Elay.done (function () {    alert ("Done1");}); Delay (dfd,5000);

Here again a global variable such as DFD, and when called to pass the DFD parameter, seems a bit ugly, to optimize:

function Ansy (time) {    var DFD = $. Deferred ();    function delay (d, time) {        setTimeout (function () {            alert ("SetTimeout executed!!!");            D.resolve ("I'm bounced out of done");        }, time);    }    Dfd.promise (delay);    Delay (dfd,time);    return delay;} Ansy. Done (function (value) {    alert ("Done said:" +value);});

Transferred from: http://www.cnblogs.com/guoyansi19900907/p/5000267.html

$.ajax () Summary of the deferred (turn)

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.