Late event subscription using when.js

Subscribe to events well after they've been fired!

by David Iglesias

HTML

<script src="https://raw.github.com/cujojs/when/1.8.1/when.js"></script>
<h1>You should do this with proper <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">Promises</a> now!</h1>

CSS

h1 { font-size: 5em; font-weight: bold; }

JavaScript

var SlowProvider = function(id, minDelay, maxDelay) {
    this.id = id;
    this.delay = Math.floor(Math.random() * maxDelay) + minDelay;
    this.deferred = null; // Will be set for slow operations...
    console.log('SlowProvider', id, 'created.');
};

SlowProvider.prototype._slowness = function() {
    // This thing simulates the end of our slow code...
    console.log(this.id, 'ready in', this.delay, 'ms.');
    this.deferred.resolve(this.id);
};

SlowProvider.prototype.doSlowStuff = function() {
    this.deferred = when.defer(); // Get the defer!
    window.setTimeout(this._slowness.bind(this), this.delay);
    console.log('Slow stuff will be done in', this.delay, 'ms.');
    return this.deferred.promise;
};

// Enqueue our first job!
var slowProvider = new SlowProvider("Stuff ", 1000, 2000);
var promise = slowProvider.doSlowStuff();
promise.then(function(id) {
    console.log('Promise resolved for provider:', id);
});

// Meanwhile, in England...
var futureSubscription = function() {
    promise.then(function(id) {
        console.log('I got late to the party, but', id, 'is done');
    });
};
window.setTimeout(futureSubscription, 7500);