#node.js #npm #oracle11g #node-oracledb
#node.js #npm #oracle11g #узел-oracledb
Вопрос:
Я использую oracledb npm package
для установления соединения с базой данных при создании node.js серверный API. Я могу получить результат, когда я делаю 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 из другого файла и когда мне нравится console.log() console.log(getDbConnection(query))
. Я получаю результат как неопределенный. Как мне это решить.
Ответ №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)
}
})
Комментарии:
1. Потрясающе, я вроде как знал, что это проблема с асинхронным вызовом, но я не мог понять, как ее решить. Спасибо. Я отмечу это как ответ, когда смогу.