Delay call--deferred.js Original code Analysis

Source: Internet
Author: User

There are times when we need to wait for the previous operation to complete before we can proceed to the next step. For example, when the AJAX implementation of the automatic form operation, the program needs to wait, once the results are returned, then proceed with a step.

At this time deferred.js this library is produced, of course, jquery also has this function. The following analysis of the principle of this library:

/** * @fileOverview jsdeferred * @author [email protected] * @version 0.4.0 * @license * jsdeferred Copyright (c) cho45 (www.lowreal.net) * * Streamlining the principles of deferred*/;//no warnings for uglifyfunctionDeferred () {return  This. Init ();}//Defining static MethodsDeferred.ok =function(x) {returnX//The default success callbackDeferred.ng =function(x) {Throwx}//determine if an instance of deferreddeferred.isdeferred =function(obj) {return!! (obj && obj._id = = =deferred.prototype._id);};//this next is a static method that hangs on the deferred. And the real-column method. Next is different.Deferred.next =function(FN) {varD =NewDeferred (); varIMG =NewImage (); varHandler =function() {D.canceller ();    D.calls (); }    //this place personally thinks the comparison is a clever second, which takes advantage of the asynchronous nature of the IMG load success or error callback.     //ensure complete collection of these. Next (). Next () ...    //in fact, the official also used two other ways to ensure compatibility, such as settimeout ....Img.addeventlistener (' Error ', Handler,false); D.canceller=function() {Img.removeeventlistener (' Error ', Handler,false); }    //this is used to trigger an IMG Load eventIMG.SRC = "Data:image/png," +Math.random (); if(fn) D.callback.ok =fn; returnD;}//This is used to simulate a more time-consuming asynchronous process//in practice, it may be the process of fetching data, such as waiting for an AJAX callbackDeferred.wait =function(n) {varD =NewDeferred (), t =NewDate (); varid = setTimeout (function() {D.calls (NewDate ()). GetTime ()-t.gettime ()); }, N* 1000); D.canceller=function() {cleartimeout (id)}; returnD;};D Eferred.prototype={_id:8888,//To determine whether it is an instance of deferred.Init:function(){         This. _next =NULL; //make deferred.isdeferred a false Judge         This. Callback ={ok:Deferred.ok, ng:Deferred.ng}return  This; }, Next:function(fun) {return  This. _post ("OK", Fun)}, calls:function(Val) {return  This. _fire ("OK", Val)}, _post:function(okng, fun) {//personally think that understanding here is the key,        //. _next Save the instance object to form a chain         This. _next =NewDeferred ();  This. _next.callback[okng] =Fun ; return  This. _next; }, _fire:function(okng, value) {varNext = "OK"; Value= This. Callback[okng] (value); //If the value here is not an instance of deferred        if(deferred.isdeferred (value)) {//Load Next TaskValue._next = This. _next; } Else {            //It means there's no next mission.            if( This. _next) This. _next._fire (Next, value); }        return  This; }} 

In order to fit the analysis, a test code is first given to facilitate the tracking of its process.

Deferred.next (function() {    alert (1)    return deferred.wait (3)}). Next (function() {    alert (2)})

Here with a chain of writing, ripe jquery people, this must not be unfamiliar. The first is to call the Deferred.next () method, return an instance of deferred, and then invoke the next () method on the instance.

The intention is to execute the first function (popup 1), and then execute the second function (popup 2), only the pipe in the notation is synchronous, but the execution is asynchronous. You might ask, why not just use settimeout?

This problem is very good, in fact, in the very circumstances, I think it is really equivalent to exchange. But SetTimeout has a premise that we need to know in advance how long it will take to complete the last step. And deferred don't need it.

And then you may ask, why not use a callback? This time I finally have no way to say anything. Just demonstrate this:

function (Next1,next2,next3,...) {    //....    // ....    Next1 (function() {        next2 (function() {            next3 (...)}    )}

Like bamboo shoots, a layer of layers. If the function is a little bit, does it look faint? Take a look at deferred's wording:

Deferred.next (function() {    next1 ();}). Next (function() {    next2 ();}). Next(function() {    next3 ()}). Next (function() {    /// ...})

Like Mahjong, the word is lined up, is a fashionable chain-style usage.

If you think it doesn't matter how you write it, then you have to combine it to see if NEXT1 is a time-consuming, indeterminate operation, but to ensure the order of execution. How did it break?

No matter how you break, anyway I choose deferred, with a fixed.

Delay call--deferred.js Original code Analysis

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.