public
Created

A JavaScript singleton object to handle asynchronous jobs.

  • Download Gist
jobs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/**
* A JavaScript singleton object to handle asynchronous jobs.
* Give it a callback to i.e. know when to close the database connection.
* @author Jacob Friis Saxberg
*/
 
module.exports = new function () {
 
this.debug = true;
var jobs = 0;
var done = false;
var callback = null;
 
function callable () {
if (done && jobs == 0 && callback != null) {
callback();
}
}
 
/**
* @param functionName The function to call when all jobs are done
*/
this.setCallback = function (functionName) {
if (typeof(functionName) != 'function') {
console.error('callback must be a function');
return false;
}
callback = functionName;
}
 
/**
* Call this when all jobs have been started.
*/
this.done = function () {
if (this.debug) {
console.log('Jobs done');
}
done = true;
callable();
}
/**
* Call this when a job starts.
*/
this.start = function () {
jobs++;
if (this.debug) {
console.log('Job start ' + jobs);
}
}
 
/**
* Call this when a job ends.
*/
this.end = function () {
jobs--;
if (this.debug) {
console.log('Job end');
}
callable();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.