我刚开始用 node.js 编码,我知道 node.js 是异步的,但不知道如何处理这个问题。
我正在查询 mysql 并按如下方式构建 JSON,
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
port : '3306',
database : 'tango_prod'
});
connection.connect();
var postsJSON = { };
var arr = new Array();
connection.query('SELECT * FROM posts LIMIT 100', function(err, rows) {
for(i=0; i < rows.length; i++){
var post_obj = {};
var post = rows[i];
post_obj.id = post.id
post_obj.actor = build_actor(post.author_id);
arr.push(post_obj);
}
console.log(JSON.stringify(arr));
});
function build_actor(actor_id){
connection.query('SELECT * FROM people WHERE id ='+actor_id+';', function(err, actor) {
connection.query('SELECT * FROM users WHERE id ='+actor.owner_id+';', function(err, user) {
var actor_obj = {};
actor_obj.id = user.id;
actor_obj.name = user.name;
actor_obj.email = user.email;
return actor_obj
});
});
}
connection.end();
我正在获取 JSON 输出,然后该build_actor
函数被调用。只有在构建演员对象后,我才需要获取 JSON。