public
Created

jQuery.whenSync() Plugin For Chaining Asynchronous Callbacks Using Deferred Objects

  • Download Gist
demo.htm
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
<!DOCTYPE html>
<html>
<head>
<title>jQuery.whenSync() For Asynchronous, Deferred Chaining</title>
 
<!-- Include jQuery and the whenSync() plugin. -->
<script type="text/javascript" src="../jquery-1.7.1.js"></script>
<script type="text/javascript" src="./jquery.whensync.js"></script>
<script type="text/javascript">
 
 
// Get a reference to the core Array slice() method for the
// debugging of our ongoing results.
var slice = Array.prototype.slice;
 
// Create a utility function that allows us to resolve the
// given deferred object after the given amount of time.
var resolver = function( deferred, result, timeout ){
 
// Resolve the deferred in the future.
setTimeout(
function(){
 
// Resolve the given deferred.
deferred.resolve( result );
 
},
timeout
);
 
};
 
 
// -------------------------------------------------- //
// -------------------------------------------------- //
 
 
// Serialize a chain of asynchronous callsbacks. Each one of
// these callbacks will receive a Deferred object so that it
// can tell the whenSync() method when to move onto the next
// asynchronous method in the chain.
var asyncChain = $.whenSync(
 
// Asynchronous method.
function( deferred ){
 
// Log the current method context.
console.log( "Method 1" );
console.log( ">Results:", slice.call( arguments, 1 ) );
 
// Reolve this callback (shortly).
resolver( deferred, "result1", 500 );
 
},
 
// Asynchronous method.
function( deferred, result1 ){
 
// Log the current method context.
console.log( "Method 2" );
console.log( ">Results:", slice.call( arguments, 1 ) );
 
// Reolve this callback (shortly).
resolver( deferred, "result2", 1000 );
 
},
 
// Asynchronous method.
function( deferred, result1, result2 ){
 
// Log the current method context.
console.log( "Method 3" );
console.log( ">Results:", slice.call( arguments, 1 ) );
 
// Reolve this callback (shortly).
resolver( deferred, "result3", 1500 );
 
}
 
);
 
 
// Bind to the asynchronous chain.
asyncChain.done(
function( result1, result2, result3 ){
 
// Log out all the results.
console.log( "Done() Binding" );
console.log( ">Results:", arguments );
 
}
);
 
 
 
</script>
</head>
<body>
<!-- Left intentionally blank. -->
</body>
</html>
jquery.whensync.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
// Define a sandbox in which the whenSync() plugin can be defined.
(function( $ ){
 
 
// Define the whenSync() jQuery plugin. This plugin is designed
// to take N-number of callbacks. Each callback will be invoked
// in order, given a Deferred object as its first invocation
// argument.
//
// callback( Deferred [, result1, result2, resultN] );
//
// Additionally, all previous results will be passed as arguments
// 2-N of the callback. Subsequent callbacks will not be invoked
// until the Deferred object is resolved.
$.whenSync = function( /* callbacks */ ){
 
// Create a master deferred object for the entire validation
// process. This will be rejected if ANY of the callback
// Deferred objects is rejected. It will be resolved only
// after ALL of the callback Deferreds are resolved.
var masterDeferred = $.Deferred();
 
// Create an array to hold the master results. As each
// callback is invoked, we are going to pass-through the
// aggregate of all the previous results.
var masterResults = [];
 
// Create a true array of callback functions (so that we
// can make use of the core Array functions).
var callbacks = Array.prototype.slice.call( arguments );
 
 
// Check to make sure there is at least one callback. If there
// are none, then just return a resolved Deferred.
if (!callbacks.length){
 
// Nothing more to do - resolve the master result.
masterDeferred.resolve()
 
// Return the promise of the result.
return( masterDeferred.promise() );
 
}
 
 
// I provide a recursive means to invoke each callback.
// I take the given callback to invoke. This callback will be
// invoked with the previously resolved master Results.
var invokeCallback = function( callback ){
 
// Create a deferred result for this particular callback.
var deferred = $.Deferred();
 
// Create a promise for our deferred object so that we
// can properly bind to the resolve / reject handlers
// for the synchronous callback step.
deferred.promise().then(
function( /* Resolve arguments. */ ){
 
// Take the current results and add them to the
// end of the master results.
masterResults = masterResults.concat(
Array.prototype.slice.call( arguments )
);
 
// This callback was resolved. Now, let's see if
// we have another callback to execute.
var nextCallback = callbacks.shift();
 
// Check for a next callback.
if (nextCallback){
 
// Recusively invoke the callback.
return( invokeCallback( nextCallback ) );
 
}
 
// No more callbacks are available - our chain of
// callbacks is complete. We can therefore
// consider the entire chain to be resolved. As
// such, we can resulve the master deferred.
masterDeferred.resolve.apply(
masterDeferred,
masterResults
);
 
},
function( /* Reject arguments */ ){
 
// This callback was rejected. We cannot proceed
// with any more steps in callback chain - we must
// reject the master deferred.
 
// Reject the master deferred and pass-through the
// rejected results.
masterDeferred.reject.apply(
masterDeferred,
arguments
);
 
}
);
 
// While the callback is intended to be asynchronous,
// let's catch any synchronous errors that happen in the
// immediate execution space.
try {
 
// Create an invocation arguments collection so that
// we can seamlessly pass-through any previously-
// resolved result. The Deferred result will always
// be the first argument in this argument collection.
var callbackArguments = [ deferred ].concat( masterResults );
 
// Call the callback with the given arguments (the
// Deferred result and any previous results).
callback.apply( window, callbackArguments );
 
} catch( syncError ){
 
// If there was a synchronous error in the callback
// that was not caught, let's return the native error.
masterDeferred.reject( syncError );
 
}
 
};
/* END: invokeCallback(){ .. } */
 
 
// Invoke the first callback.
invokeCallback( callbacks.shift() );
 
// Return the promise of the master deferred object.
return( masterDeferred.promise() );
 
};
 
 
})( jQuery );
// End jQuery plugin.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.