的NodeJS异步数据库函数需要同步的答案 +

我是新来的NodeJS和我写,需要从我去过的所有的函数应该是在这种情况下,读QUERY我的MySQL数据库,并返回代码,我非常希望服务器能够对其他事件作出回应而这个地方是轨迹查询请求。然而,它并不特别增光查询,并只返回值GaGa的。也许我应该将其标记(如果这是你的答案 CodeGo.net,这将是巨大改变编码的采样率)反正,这里是我的函数。它给出错误回报是不确定的在这一点上最后一行的“近了。有什么建议?

function get_current_username(current_user_id) {
 console.log(' | Entered get_current_username');
 sqlq = 'SELECT username FROM users WHERE id = ' + current_user_id;
 connection.query(sqlq, function(err, rows, fields) {
  if (err) throw err;
  var current_username = rows[0].username;
  console.log(' | the current_username =' + current_username);  
 });
return current_username;

} +

本文地址 :CodeGo.net/571327/

-------------------------------------------------------------------------------------------------------------------------

1. 通过在回调函数get_current_username然后调用回调函数从内部connect.query论回调:

function get_current_username(current_user_id, callback) {
 console.log(' | Entered get_current_username');
 sqlq = 'SELECT username FROM users WHERE id = ' + current_user_id;
 connection.query(sqlq, function(err, rows, fields) {
  if (err) throw err;
  var current_username = rows[0].username;
  console.log(' | the current_username =' + current_username);  
  callback(current_username);
 });
}

当你去这个函数,那么,你想要回:

get_current_username(12345, function(username) {
 console.log("I am " + username);
});

您还可以检查出承诺/期货。我觉得我不能够支持这些司法解释,我就跳下去大概的了解所承诺的连结此StackOverflow问题。 这是结构的决定,但-人宁愿回调,特别是如果写模块由第三方供。 (而事实上,它可能是最好让你的头完全缠回调在学习阶段在这里,之前通过类似承诺。) +