-
-
Save webjay/1274105 to your computer and use it in GitHub Desktop.
A JavaScript singleton object to handle asynchronous jobs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment