Thr*_*ad7 3 javascript asynchronous node.js
我是nodejs的新手,我正在编写一些代码,需要查询我的MySQL数据库并从给定的user_id返回一个用户名.我一直在读你所有的功能应该是异步的.在这种情况下,理想情况下我希望服务器能够在进行此查询时响应其他事件请求.但是,它不是一个特别大的查询,只返回一个值.也许我应该让它同步?(如果这是你的答案,改变它的示例代码会很棒)无论如何,这是我的功能.它在最后一行"return current_username;"附近发出错误 因为当前current_username未定义.有什么建议?
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;
Run Code Online (Sandbox Code Playgroud)
}
传入一个回调函数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);
});
}
Run Code Online (Sandbox Code Playgroud)
当你去使用这个功能时,你会做类似的事情:
get_current_username(12345, function(username) {
console.log("I am " + username);
});
Run Code Online (Sandbox Code Playgroud)
您还可以查看承诺/期货的使用情况.我有一种感觉,我将无法解释这些正义,所以我将链接到这个关于理解Promises的StackOverflow问题.
这是一个架构决策 - 有些人更愿意使用回调,特别是如果编写一个模块供第三方重用.(事实上,在采用像Promise这样的东西之前,最好让你的头脑完全围绕这里的学习阶段的回调.)
| 归档时间: |
|
| 查看次数: |
2233 次 |
| 最近记录: |