我在创建node.js后端API时使用oracledb npm package
与数据库建立连接。我可以在console.log(result.rows)
以下是功能代码
getDbConnection: function(query) {
var connectInfo= [EnvConfig.getConnectionHostName(), EnvConfig.getConnectionPort()]; // Array of hostname and port
var connectHost = connectInfo.join(':'); // join hostname and port with ':'
var connectionAttr = [connectHost, EnvConfig.getConnectionSID()]; // hostname:port and SID
var connectString = connectionAttr.join('/'); // creating the connection string like 'hostname:port'
console.log(connectString);
// creating a oracle connection
oracledb.getConnection(
{
user: EnvConfig.getConnectionUserName(),
password: EnvConfig.getConnectionPassword(),
connectString: connectString
},
function (err, connection) {
if(err) {
console.log(err.message);
return;
}
connection.execute(
query, function(err, result) {
if(err) {
console.log(err.message);
return;
}
console.log(result.rows); // I get result here
return result.rows; // return result on success
}
);
}
);
}
我从其他文件中调用getDbConnection函数,当我调用{.1}}之类的console.log()时。我得到的结果是未定义的。我该如何解决这个问题。
答案 0 :(得分:1)
你无法获得这样的数据。像这样的回归不会在这里工作
由于它在异步性质下工作,你可以做一件事来使用回调函数来获得这样的结果
DbConnection: function(query,callback) {//pass callback as parameter
var connectInfo = [EnvConfig.getConnectionHostName(), EnvConfig.getConnectionPort()]; // Array of hostname and port
var connectHost = connectInfo.join(':'); // join hostname and port with ':'
var connectionAttr = [connectHost, EnvConfig.getConnectionSID()]; // hostname:port and SID
var connectString = connectionAttr.join('/'); // creating the connection string like 'hostname:port'
console.log(connectString);
// creating a oracle connection
oracledb.getConnection({
user: EnvConfig.getConnectionUserName(),
password: EnvConfig.getConnectionPassword(),
connectString: connectString
},
function(err, connection) {
if (err) {
console.log(err.message);
return callback(err);
}
connection.execute(
query,
function(err, result) {
if (err) {
console.log(err.message);
return callback(err);
}
console.log(result.rows); // I get result here
return callback(null,result.rows); // return result on success
}
);
}
);
}
并像这样打电话
//Use your function with callback
getDbConnection(query,function(err,result){
if(!err){
console.log(result)
}
})