Skip to content

Instantly share code, notes, and snippets.

@corbanbrook
Created February 14, 2012 04:34
Show Gist options
  • Select an option

  • Save corbanbrook/1823570 to your computer and use it in GitHub Desktop.

Select an option

Save corbanbrook/1823570 to your computer and use it in GitHub Desktop.
Ordered function loader with load.next helper and async callback support
var load = (function() {
var loads = [];
var nextIndex = 0;
var _Load = {
run: function() {
this.next();
},
next: function() {
var load = loads[nextIndex];
if (load && typeof load.func === "function") {
console.log("Running <" + load.desc + ">");
nextIndex++;
var nextFunctionReady = (function(index) {
return function() {
return nextIndex === index;
};
}(nextIndex));
load.func.apply(this, arguments);
if (!load.hasAsyncCallback && nextFunctionReady()) {
_Load.next.apply(this, arguments);
}
} else {
console.log("END");
}
},
add: function(desc, func, hasAsyncCallback) {
loads.push({ desc: desc, func: func, hasAsyncCallback: hasAsyncCallback });
}
};
return _Load;
}());
// function with an asyncronous callback
var a = function(callback) { console.log("A"); setTimeout(function() { callback("Hello from A"); }, 1000); };
// function with params and syncblocking callback
var b = function(response, callback) { if (!response) { throw "Err: no response"; } console.log("B", response); callback(); };
// function with no params and syncblocking callback
var c = function(callback) { console.log("C"); callback(); };
// function with no callback -- next function will be called in the chain automatically
var d = function() { console.log("D"); };
// function with an asyncronous callback
var e = function(callback) { console.log("E"); setTimeout(function() { callback(); }, 1000); };
// function with no callback -- will end
var f = function() { console.log("F"); };
load.add("A", function() { a(load.next); }, true); // hasAsyncCallback needs to be specified so it does not automatically call next.
load.add("B", function(response) { b(response, load.next); }, true); // hasAsyncCallback is specified on a syncblocking callback, doesnt mind.
load.add("C", function() { c(load.next); }); // normal sync blocking callback
load.add("D", function() { d(); }); // no callback given
load.add("E", function() { e(load.next); }, true); // another async callback
load.add("F", function() { f(); }); // another no callback -- should end
// Start the loader
load.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment