Building JSON with Node.js with multiple queries
asynchronous, javascript, node.js
Solution
You have to do it asynchronously with callbacks:
connection.query('SELECT * FROM posts LIMIT 100', function(err, rows) {
for(i=0; i < rows.length; i++){
build_actor(post.author_id, function(actor){
var post_obj = {};
var post = rows[i];
post_obj.id = post.id
post_obj.actor = actor;
arr.push(post_obj);
if(arr.length === rows.length)
console.log(JSON.stringify(arr));
});
}
});
function build_actor(actor_id, callback){
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;
callback(actor_obj);
});
});
}
Problem
I have just started coding with node.js, I understand that node.js is asynchronous but not sure how to deal with this problem. I'm querying mysql and building a JSON as follows, ``` 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(); ``` I'm getting JSON output and later the `build_actor` function is getting called. I have to get JSON only after building the actor object.