Last active
October 1, 2015 08:28
-
-
Save adrianvlupu/760901f66f9677defd7c to your computer and use it in GitHub Desktop.
async nodejs module
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
/** | |
* An async module | |
* @module asyncModule | |
*/ | |
var q = require('q'); | |
var debug = require('debug')('asyncModule'); | |
debug.log = console.log.bind(console); | |
var service = (function () { | |
//private | |
var lazyDependency; | |
var initPromise; | |
//constructor | |
var service = function () { | |
var self = this; | |
initPromise = q.promise(function (resolve, reject, notify) { | |
//initialize async module | |
setTimeout(function () { | |
lazyDependency = {}; | |
lazyDependency._method = function (message, callback) { | |
callback(message + " altered"); | |
}; | |
//resolve defer | |
resolve(lazyDependency); | |
}, 5000); | |
}); | |
}; | |
service.prototype.myMethod = function (message, callback) { | |
var self = this; | |
//queue function | |
initPromise.then(function (obj) { | |
debug(self.name); | |
obj._method(message, function (msg) { | |
callback(null, msg); | |
}); | |
}); | |
}; | |
service.prototype.configure = function (options) { | |
this.name = options.name; | |
}; | |
return service; | |
})(); | |
new service().myMethod('test', function (err, message) { | |
console.log('response', message); | |
}); | |
module.exports = new service(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment