Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"... so the done callback is only called when all deferred are resolved, including those added later" makes no sense, however I think I know what you mean.</p> <p>If I understand correctly then you want what might be termed a "re-firable when()" - something like this (based on jQuery) :</p> <pre><code>function PromiseSet(memory, once) {//javascript Constructor var flags = []; if(memory) flags.push('memory'); if(once) flags.push('once'); var promises = [], doneCallbacks = $.Callbacks(flags.join(' ')), failCallbacks = $.Callbacks(flags.join(' ')); this.add = function(promise, val) { promises.push(promise); if(val) { this.fire(val); } return this; }; this.done = function(fn) { doneCallbacks.add(fn); return this; }; this.fail = function(fn) { failCallbacks.add(fn); return this; }; this.fire = function(val) { val = val || null; $.when.apply($, promises).then( function() { doneCallbacks.fire(val); }, function() { failCallbacks.fire(val); } ); return this; }; return this; } </code></pre> <p><em>untested</em></p> <p>All methods return this to make them chainable.</p> <p>If I've written the constructor correctly, then you can control its detailed behaviour by passing booleans to <code>new PromiseSet()</code>. For your propised usage, I think you need to pass <code>(true, false)</code>, but try other settings to see what happens.</p> <p>Sample sequence :</p> <pre><code>var myPromiseSet = new PromiseSet(true, false); myPromiseSet.add(promise1); myPromiseSet.add(promise2).add(promise3); myPromiseSet.done(myDoneFunction).fail(myFailFunction); myPromiseSet.fire("foo"); myPromiseSet.add(promise4).fire(); </code></pre>
 

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