在函数中使用node-mysql [英] Using node-mysql in a function
问题描述
我对Node.js很陌生,有一个问题.
I'm very new to nodejs and have a question.
尝试创建一个函数,该函数将调用我从表中提及其ID的任何字段的值:
Trying to create a function that will call the value of any field where I mention its ID from a table:
function getUserInfo (userID, dynamicField) {
var query = connection.query('SELECT '+dynamicField+' from users WHERE userID = '+connection.escape(userID));
query.on('result', function(row) {
return(row.dynamicField);
});
};
console.log(getUserInfo(8, userEmail)) //this should get me the userEmail value of the user with userID=8
但是,我得到未定义".如果我使用console.log而不是return,它将记录该值,但这没有用做在其他函数中获取值的函数.
However, I get "undefined". If I use console.log rather than return, it logs the value but this has no use as a function to be used inside other functions to get a value.
如果能获得修改该功能的帮助,我将感到非常高兴.
I will be glad if I can get help for modifying the function.
推荐答案
这是async/nodejs初学者中的常见错误.您实际上已经将async函数包装在sync函数中,这破坏了节点事件循环的性质.返回表达式需要用回调代替.见下文:
This is a common mistake amongst async/nodejs beginners. You have essentially wrapped an async function inside a sync function which breaks down the nature of node's event loop. The return expression needs to be replaced with a callback. See below:
// Method
function getUserInfo (userID, dynamicField, callback) {
var query = connection.query('SELECT '+dynamicField+' from users WHERE userID = '+connection.escape(userID));
query.on('result', function(row) {
callback(null, row.dynamicField);
});
};
// Implementation
getUserInfo(8, userEmail, function(err, result){
console.log(err || result);
});
按照惯例,在Node.js中,我们总是首先在回调中传递一个错误对象.在这种情况下,由于没有错误要捕获,因此我们将null替换为它.
By convention, in Nodejs we always pass an error object first in the callback. In this case since there is no error to capture, we pass null in its place.
这篇关于在函数中使用node-mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!