Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active December 15, 2015 13:39
Show Gist options
  • Save justinobney/5268969 to your computer and use it in GitHub Desktop.
Save justinobney/5268969 to your computer and use it in GitHub Desktop.
Promise Bag - Send promises in and monitor begin and duration while promises are being resolved & all promises resolved.
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, browser:true, devel:true, jquery:true, indent:4, maxerr:50, node:true */
/* global _ */
(function ($, _) {
"use strict";
//Actual app logic
var PromiseCue = function (options) {
var fn = function () {},
promises = [];
_.defaults(options, {
start: fn,
complete: fn
});
var add = function (promise) {
if (promises.length === 0) options.start();
// push new promise
promises.push(promise);
// re-register the when
_.when.apply(_, promises).done(function () {
var doneCount = _.filter(promises, function (e) {
return e.state() === "resolved";
}).length;
if (doneCount === promises.length) (function () {
promises = [];
options.complete();
}) ();
});
};
return {
Add: add
};
};
var MyApp = (function () {
// Usage Example / Test
var workingbar = $('.working'),
requests = [];
var showWorking = function () {
workingbar.text('Working...').fadeIn();
_.wait(3000).then(function () {
workingbar.text('Still Working...');
});
};
var hideWorking = function () {
workingbar.fadeOut();
};
var promiseQ = PromiseCue({
start: showWorking,
complete: hideWorking
});
// For Mocking AJAX Calls
function fakeJax() {
var req = _.Deferred();
var timeout = getRandomInt(0, 20) * 500;
requests.push(req);
var reqNum = 'request ' + requests.length;
log('faking ajax ' + reqNum + ' for ' + (timeout / 1000) + ' seconds');
req.done(function () {
log(reqNum + ' is done');
});
_.wait(timeout).then(req.resolve);
return req.promise();
}
$('#fakeJax').click(function(e){
var promise = fakeJax();
promiseQ.Add(promise);
});
})();
// Utility
_.wait = function (time) {
return _.Deferred(function (dfd) {
setTimeout(dfd.resolve, time);
}).promise();
};
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function log(message) {
var _console = $('.console');
$('<p>').text(message).prependTo(_console);
}
})($, _);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment