<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...
};
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);
return this.deferred.promise;
};
// My innocent code!
var ProviderHandler = function(numProviders, minDelay, maxDelay) {
this.promises = [];
this.numProviders = numProviders;
this.minDelay = minDelay;
this.maxDelay = maxDelay;
};
ProviderHandler.prototype._createPromises = function() {
var promises = [];
for (var i = 0; i < this.numProviders; i++) {
var slowProvider = new SlowProvider(i, this.minDelay, this.maxDelay);
promises.push(slowProvider.doSlowStuff());
}
return promises;
};
ProviderHandler.prototype.testPromises = function() {
var promises = this._createPromises(); // Enqueue a bunch of async operations
when.any(promises).then(function(id) {
console.log('First request done!', id);
});
when.some(promises, 7).then(function(ids) {
console.log('First 7 promises done!', ids);
});
when.all(promises).then(function() {
console.log('All done!!');
});
};
var myApp = new ProviderHandler(100, 500, 2000);
myApp.testPromises();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.