我需要能够通过查询redis中的值来导出模块的变量,但我不知道如何异步执行。
这就是我尝试过的,其中getconfig()是一个返回从redis:查询的变量的函数
var exports = {};
module.exports = exports;
getconfig(function(config){
exports.ConnectionString = {
Server: config.db.server,
Login: config.db.userName,
Database: config.db.database,
Password: config.db.password,
Port: 1433,
Timeout:10000
};
exports.poolSize = 1000;
exports.poolIdleTimeout = 30000000;
exports.tdsServerPort = 88888;
console.log(exports);
})
但这并不奏效。如何返回这些导出变量?
我使用以下简化示例尝试了@Peter Lyons的建议:
module.exports = {
ConnectionString: getDb,
poolSize: 1000,
poolIdleTimeout: 30000000,
tdsServerPort: 88888
}
function getDb(cb){
var dat = {
Server:'192.168.42.4',
Login: 'XXXX',
Database: 'MYDB',
Password: 'PASS',
Port: 1433,
Timeout:10000
};
cb(null,dat);
}
但当它被调用时,它会将连接字符串作为函数返回,并且不会进行评估:
{ ConnectionString: [Function: getDb],
poolSize: 1000,
poolIdleTimeout: 30000000,
tdsServerPort: 88888 }
模块用于代码和静态数据。函数、常量等。数据库中的数据不属于模块导出。这非常不合常规,有些不合逻辑。然而,传统而直接的是一个查询和数据库并调用带有结果的回调的函数。
function getConnectionString(callback) {
getConfigFromRedis(function (error, config) {
if (error) {
callback(error)
return
}
var connectionString = {
Server: config.db.server,
......etc
}
callback(null, connectionString)
})
}
module.exports = {
getConnectionString: getConnectionString
}
听起来您正在使用另一个工作方式如下的模块:
var my_module = require('my_module');
var thing = require('thing')(my_module);
如果是这样的话,你将不得不以某种方式包装你的代码,无论是彼得·莱昂斯在他的回答评论中描述的,还是像这样。
/////// in your module ///////
module.exports = {
ConnectionString: {},
poolSize: 1000,
poolIdleTimeout: 30000000,
tdsServerPort: 88888
}
function setup(cb){
// just using GET to simplify because I have no idea how your db is set up
redis_client.get('connection_data_key', function(err, result) {
exports.ConnectionString = result;
cb(err);
}.bind(this));
}
////// in your main code //////
var my_module = require('my_module');
my_module.setup(function(err) {
var thing = require('thing')(my_module);
// the rest of your code dependent on 'thing' goes here
});