[英]How to get data from a different node.js code
I have a code snippet in the db.js as below, 我在db.js中有一个代码段,如下所示,
exports.asyncGetAllData = function () {
connection.connect(function(err) {
connection.query(sqlGetAllData, function (err, result) {
if (err) reject(err);
else
{
//console.log(result);
}
});
});
};
And I want to get the result data when I called the function in app.js as below. 而且我想在app.js中调用函数时获取结果数据,如下所示。
app.get('/test/getPriceTrend', function(req, res) {
console.log('SERVER::getPriceTrend');
console.log(req.url);
var data = db_connection.asyncGetAllData(); //data is undefined
console.log(data);
res.setHeader('Accept', 'application/json');
res.writeHead(res.statusCode);
//The following piece of code will send information from the database
res.write(JSON.stringify({"hello":"world"}));
res.end();
});
As you can see, when I tried to fetch data from db.js, it shows in the console window "the data is undefined". 如您所见,当我尝试从db.js中获取数据时,它在控制台窗口中显示“数据未定义”。 How can I solve this issue?
我该如何解决这个问题? Any suggestion?
有什么建议吗?
Thanks in advance, 提前致谢,
Looks like you are calling for data using async method and not waiting for the response. 看起来您正在使用async方法调用数据,而不是等待响应。
var data = db_connection.asyncGetAllData(); //data is undefined
console.log(data);
Either use a function that would get you SyncData or use a callback as in: 使用将获取SyncData的函数或使用如下所示的回调:
exports.asyncGetAllData = function (cb) {
connection.connect(function(err) {
connection.query(sqlGetAllData, function (err, result) {
if (err) reject(err);
else
{
//console.log(result);
cb(data);
}
});
});
};
var data = db_connection.asyncGetAllData(function(data) {
console.log(data);
res.write(JSON.stringify(data));
res.end();
});
The easiest way to do this is to create a callback function that you pass to asyncGetAllData()
最简单的方法是创建一个传递给
asyncGetAllData()
的回调函数。
Your function would look more like this: 您的函数看起来像这样:
exports.asyncGetAllData = function (callback) {
connection.connect(function(err) {
connection.query(sqlGetAllData, callback)
})
}
Then in you app.js
you pass the callback in: 然后在您的
app.js
传递回调:
db_connection.asyncGetAllData(function(err, result{
if (err) reject(err);
else
{
//console.log(result);
}
})
You could also adjust asyncGetAllData
to return a promise,which might make things a little prettier. 您还可以调整
asyncGetAllData
以返回诺言,这可能会使事情变得更漂亮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.