I am completely confused in the context inside the promise of Q. I do not think that Q is specific, but common with all promises. What the hell is the context thisinside the class?
This code uses TypeScript, now everything is static, because basically it was not possible to do something non-static. This code works great.
I tried to add an instance variable private _config;and use the method _getConfigto set _configin the constructor. But when I used the this._configinside of the method checkMongodbConnection, well, it was not the same object as the method _getConfig(). (I watched state variables in debug mode)
Therefore, I assume that thisinside the class, because I call the code from the promise of Q, there is no context for the instance of the class.
I am wondering if using promises is really a good idea, if I run into context problems, the code will be a lot more complicated to understand and debug. I would be happy to understand why I made the choice as a result. I do not want to lose the context of the class instance, too complicated. I am afraid to use technology that will actually complicate the situation; I prefer the opposite hell to this.
export class App {
private static _getConfig(){
if(typeof __config !== "undefined"){
return __config;
}else{
require('./../../shared/lib/globals/services');
return configHelper.load('_serverConfig', require('./../../shared/config/_serverConfig.json').path.config, __dirname + '/../../');
}
}
public static checkMongodbConnection(){
var config = App._getConfig();
var deferred: any = Q.defer();
if(config.game.checkMongodb){
var mongodbConfig = require('./../../shared/config/mongodb.json')['development'];
mongoose.connect('mongodb://' + mongodbConfig.host + '/' + mongodbConfig.database);
var db: mongoose.Connection = mongoose.connection;
db.on('error', function(err) {
deferred.reject('Mongodb is not running, please run the mongod process: \n' + err)
});
db.once('open', function callback () {
db.db.close();
deferred.resolve();
});
}else{
deferred.resolve();
}
return deferred.promise;
}
public static checkRedisConnection(){
var config = App._getConfig();
var deferred: any = Q.defer();
if(config.game.checkRedis) {
var redisClient:any = redis.createClient();
redisClient.on("error", function (err) {
deferred.reject(err);
});
redisClient.set("keyTest", true);
redisClient.get("keyTest", function (err, reply) {
if (err) {
deferred.reject("Redis is not running, please make sure to run redis before to start the server. \n" + err);
} else {
deferred.resolve();
}
});
}else{
deferred.resolve();
}
return deferred.promise;
}
}
Code calling the class:
Q.fcall(App.checkRedisConnection)
.then(App.checkMongodbConnection)
.then(function(result) {
}, console.error);