Skip to content

Instantly share code, notes, and snippets.

@iamahuman
Created May 6, 2017 23:31
Show Gist options
  • Save iamahuman/ff3b287617eece2dddf24aa30a8ae8fe to your computer and use it in GitHub Desktop.
Save iamahuman/ff3b287617eece2dddf24aa30a8ae8fe to your computer and use it in GitHub Desktop.
Simple async.js-like dependent task processing
function process_reqs (reqs) {
var dependents = {}; // name -> [dependents]
var completed = {};
var pending_cnts = {};
var hasOwn = Object.prototype.hasOwnProperty;
var leaf_tasks = [];
for (var key in reqs) {
if (!hasOwn.call(reqs, key)) continue;
var deplist = reqs[key].deps;
pending_cnts[key] = deplist.length;
if (deplist.length === 0) {
leaf_tasks[leaf_tasks.length] = key;
} else {
for (var i = 0; i < deplist.length; i++) {
var dep = deplist[i], ds;
if (hasOwn.call(dependents, dep)) {
ds = dependents[dep];
} else {
ds = dependents[dep] = [];
}
ds[ds.length] = key;
}
}
}
schedule (leaf_tasks);
function createCompletionCallback (task) {
return function () {
var targets = dependents[task];
var sched_tasks = [];
if (!targets) return;
delete dependents[task];
completed[task] = [].slice.call(arguments);
for (var i = 0; i !== targets.length; i++) {
var key = targets[i];
if (!--pending_cnts[key]) { // completed
sched_tasks[sched_tasks.length] = key;
}
}
schedule (sched_tasks);
}
}
function schedule (sched_tasks) {
sched_tasks.sort(function (a, b) {
return reqs[b].priority - reqs[a].priority;
});
while (sched_tasks.length) {
var sched_key = sched_tasks.pop();
//console.log("processing " + sched_key + "...");
var cc = createCompletionCallback(sched_key);
try {
reqs[sched_key].process(completed, cc);
} catch (e) {
console.log("an error occured while processing " + sched_key + ": " + e.stack);
cc(e, null);
}
cc = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment