XmlAspect.org/Xml4jQuery/Promise Chain

From ApiFusion
Jump to: navigation, search

Promise Chain

All Xml4jQuery methods and the jQuery ones which following them are executed asynchronously. In the expression

.sleep(100) // creates Promise Chain
.addClass('pending') // executed after 0.1 seconds
.ajax(url) // upon adding class
.removeClass('pending'); // after XHR completed

after sleep(100) each call is executed only upon previous step resolved.

To support this asynchronous chaining Xml4Jquery plugins returning a Promise Chain object. The new Promise object is going to be resolved upon

  1. resolving the parent promise
  2. successful execution of the method on collection with given parameters

Promise Chain is a façade for jQuery selection object and mimics its methods. There are several methods which are not implemented as jQuery plugins and available only in the Promise Chain.

  • $then( onOK, onError) analog of W3C Promise then(). The previously resolved results in call chain are passed as onOK callback parameters
  • break() interrupts the Promise Chain execution
  • destroy() stops the execution, releases all allocated resources and destroys the Promise Chain as after the current segment as in front.

Resolved results

The each segment execution result is saved and passed as parameter in callbacks of some Promise Chain methods like $then() or sleep()

.sleep(100) // 100 is a segment value
.ajax( url ) // say XHR returns {"key":"val"}
.sleep( 200, function(a0, a1){    return 20;  }) // the callback return value is a segment value; arguments[ {"key":"val"}, 100 ]
.$then( function( a0, a1, a2 ){    return 30; }) // arguments [20, {"key":"val"}, 100] 
.sleep( 300, function( a0, a1, a2, a3){} ); // arguments [30, 20, {"key":"val"}, 100 ]

Callback arguments

While callback arguments are filled with segment resolved values, it is possible to pass then from the call parameters:

.sleep( function(a0, a1){    return 20;  }) // arguments[ 100 ]
.$then(  myCallback, "abc", onErr ); // second function in the arguments is an error callback

function myCallback( a0, a1, a2 ){} // arguments [ "abc", 20, 100 ]

In callback arguments the vales from the call will be followed by Promise Chain resolved values.

Recurrent sequences

Transforms the data taken from url after click into $('.schedule'); the chain is reinitialized on each click.

var page = 0;
.$then() // as Promise Chain 
.transform( xsl, $('.schedule') );

Appends data page every second until last page reached.

var page = 0;
.interval(1000) // repeat every second
.$then( function(){   return ajax(url+page) }// ajax() returns promise, segment is going to be resolved with its resolved value.
.$then( function(data)
    {   if( !data ) // no more data available
            return this.destroy();   // whole chain could be removed
        return this.transform( data, xsl );
.append(); // transform results will be added to $('.schedule')