Last active
December 26, 2015 19:09
-
-
Save suda/7199880 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * Module allowing to use Azure Mobile Services database on server side | |
| * in a synchronous manner. | |
| * | |
| * Singleton based on http://simplapi.wordpress.com/2012/05/14/node-js-singleton-structure/ | |
| * | |
| * @example | |
| * var synchronizer = require('query-synchronizer'); | |
| * synchronizer.read(table, function(results) { | |
| * // Do something with the results | |
| * }); | |
| * synchronizer.read(second_table, function(results) { | |
| * // Do something with the second results | |
| * | |
| * synchronizer.read(third_table, function(inner_results) { | |
| * // Do something with nested results | |
| * } | |
| * }); | |
| * synchronizer.done(function(){ | |
| * // This will be executed only when previous reads are done | |
| * }); | |
| * | |
| * @author Wojtek Siudzinski <admin@suda.pl> | |
| * | |
| */ | |
| var singleton = function singleton(){ | |
| //defining a var instead of this (works for variable & function) will create a private definition | |
| var requestsToEnd = 0; | |
| this.read = function(query, callback){ | |
| requestsToEnd++; | |
| query.read({ | |
| success: function(results) { | |
| callback(results); | |
| requestsToEnd--; | |
| } | |
| }); | |
| return this; | |
| }; | |
| this.done = function(callback){ | |
| var interval = setInterval(function() { | |
| if (requestsToEnd <= 0) { | |
| clearInterval(interval); | |
| callback(); | |
| } | |
| }, 1); | |
| return this; | |
| }; | |
| if(singleton.caller != singleton.getInstance){ | |
| throw new Error("This object cannot be instanciated"); | |
| } | |
| } | |
| singleton.instance = null; | |
| /** | |
| * Singleton getInstance definition | |
| * @return singleton class | |
| */ | |
| singleton.getInstance = function(){ | |
| if(this.instance === null){ | |
| this.instance = new singleton(); | |
| } | |
| return this.instance; | |
| } | |
| module.exports = singleton.getInstance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment