gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:02:15 25 4
gpt4 key购买 nike

我对 Q promise 中的上下文完全感到困惑。我认为这不是特定于 Q 的,而是具有所有 promise 的一般性。 this 在类中的上下文到底是什么?

此代码使用 TypeScript,现在一切都是静态的,因为我基本上失败做任何非静态的事情。此代码工作正常。

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

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

我想知道使用 promises 到底是不是个好主意,如果我遇到上下文问题,代码只会很多更难以理解和调试。我很乐意理解为什么并因此做出选择。我不想丢失类实例上下文,这太棘手了。我害怕使用实际上会使事情变得更复杂的技术,我更喜欢回调 hell

///<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;
}
}

调用类的代码:

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

最佳答案

promises/A+ 规范明确规定 promise 链中 this 的值始终未定义(严格模式)或全局对象:

2.2.5 onFulfilled and onRejected must be called as functions (i.e. with no this value).

指定 here .

如果您没有使用像 Bluebird 这样允许显式设置 this 的 promise 库(通过 .bind),您仍然可以使用 TypeScript 的粗箭头(也在 ES6 中) ) 用词汇 this 来调用一些东西。

关于javascript - Q.js, promises, classes 和 "this",上下文是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23591165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com