Q.js,promises,classes和"this",上下文是什么?

Vad*_*est 4 javascript node.js promise q

我对Q承诺中的上下文感到困惑.我不认为这是Q的具体,但一般都有所有的承诺.this一个班级里面的背景到底是什么?

这段代码使用TypeScript,现在一切都是静态的,因为我基本上没有做任何非静态的事情.这段代码工作正常.

我尝试添加一个private _config;实例变量并使用该_getConfig方法_config在构造函数中设置.但是当我this._config在方法中使用时checkMongodbConnection,它与_getConfig()方法返回的对象不同.(我在调试模式下观察了变量状态)

所以我想this,在一个类中,因为我从Q promise中调用代码,所以没有类实例上下文.

我想知道,如果使用的承诺是一个好主意,毕竟,如果我碰上的语境问题的代码将只是很多更难理解和调试.我很感激理解为什么并做出选择.我不想丢失类实例上下文,这太麻烦了.我害怕使用一种让事情变得更复杂的技术,我更喜欢回调地狱.

///<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;
    }
}
Run Code Online (Sandbox Code Playgroud)

调用类的代码:

Q.fcall(App.checkRedisConnection)
    .then(App.checkMongodbConnection)
    .then(function(result) {
         // run server
    }, console.error);
Run Code Online (Sandbox Code Playgroud)

Ben*_*aum 7

promises/A +规范明确规定thispromise链中的值总是未定义(严格模式)或全局对象通过:

2.2.5 onFulfilled和onRejected必须作为函数调用(即没有此值).

在这里指定.

如果您没有使用像Bluebird这样允许this明确设置(通过.bind)的承诺库,您仍然可以使用TypeScript的胖箭头(也在ES6中)来调用词法this.

  • 胖箭头是较短的函数语法,但它们也在词汇上绑定'this'值. (2认同)