Q.js, promises, classes and "this", what is the context?

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.

///<reference path='./def/defLoader.d.ts'/>    
export class App {

    /**
     * Constructor.
     * Load the config.
     * @return {}
     */
    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 + '/../../');
        }
    }

    /**
     * Check that the mongoose connection open correctly, meaning that the mongod process is running on the host.
     * @return {Q.Promise<T>|Function}
     */
    public static checkMongodbConnection(){
        var config = App._getConfig();

        // Building promise
        var deferred: any = Q.defer();

        if(config.game.checkMongodb){
            // Retrieves the mongoose configuration file, the env doesn't matter here.
            var mongodbConfig = require('./../../shared/config/mongodb.json')['development'];

            // Try mongoose connexion
            mongoose.connect('mongodb://' + mongodbConfig.host + '/' + mongodbConfig.database);

            // Bind connexion
            var db: mongoose.Connection = mongoose.connection;

            // Get errors
            db.on('error', function(err) {
                deferred.reject('Mongodb is not running, please run the mongod process: \n' + err)
            });

            // If the connexion seems to be open
            db.once('open', function callback () {
                // Close it
                db.db.close();

                // Resolve promise
                deferred.resolve();
            });
        }else{
            deferred.resolve();
        }

        // Get back promise
        return deferred.promise;
    }

    /**
     * Check that the redis connection is open, meaning that the redis-server process is running on the host.
     * @return {Q.Promise<T>|Function}
     */
    public static checkRedisConnection(){
        var config = App._getConfig();

        // Building promise
        var deferred: any = Q.defer();

        if(config.game.checkRedis) {
            // Create the redis client to test to connexion on server
            var redisClient:any = redis.createClient();

            // Get client errors
            redisClient.on("error", function (err) {
                deferred.reject(err);
            });

            // Try applying a key
            redisClient.set("keyTest", true);

            // Now key is applied, try getting it
            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();
        }

        // Get back promise
        return deferred.promise;
    }
}

Code calling the class:

Q.fcall(App.checkRedisConnection)
    .then(App.checkMongodbConnection)
    .then(function(result) {
         // run server
    }, console.error);
+4
source share
1 answer

promises/A + , this undefined ( ) :

2.2.5 onFulfilled onRejected (.. ).

.

, ​​ Bluebird, this ( .bind), TypeScript ( ES6) - this.

+7

Source: https://habr.com/ru/post/1540092/


All Articles