Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand you correct, you want to chain requests or other asynchronous events? Then the <a href="http://blogs.msdn.com/b/ie/archive/2011/09/11/asynchronous-programming-in-javascript-with-promises.aspx" rel="nofollow">promises</a> pattern is an elegant solution.</p> <p>JQuery already implements it with the <a href="http://api.jquery.com/category/deferred-object/" rel="nofollow">Deferred object</a>.</p> <p>With JQuery 1.8+ request chaining can be as simple as:</p> <pre><code>$.ajax(...).then( function() { return $.ajax(...); } ).then( function() { return $.ajax(...); } ); </code></pre> <p>But you also can build a more dynamic and complex architecture around it. For example you could implement your queue such that it always stores the last unresolved promise so that you can attach new handlers to it while it is already active.</p> <p><strong>Generic Example:</strong></p> <pre><code>var Queue = function() { // start with resolved promise var promise = $.Deferred().resolve(); this.add = function(handler) { // chain and replace latest with next promise promise = promise.then(function() { var deferred = $.Deferred(); handler(deferred); return deferred; }).promise(); } }; var q = new Queue(); q.add(function(deferred) { setTimeout(function() { alert('handler 1'); deferred.resolve(); }, 1000); }); q.add(function(deferred) { setTimeout(function() { alert('handler 2'); deferred.resolve(); }, 1000); }); </code></pre> <p><strong><a href="http://jsfiddle.net/NsCPe/" rel="nofollow">JSFiddle demo</a></strong></p> <p>Here the handlers get a deferred object as parameter and are responsible to resolve (or reject) it if they are "done". Another, more flexible, possibility would be that the handlers have to create the deferred object by themselves and return its promise, this way you also can use other promises like those which are returned by $.ajax</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload