0

I want to render results from multiple queries to my template from NodeJS.

  connection.query("select * from table1",function(err,rows){

        if(!err) {

            var data1 = JSON.parse(JSON.stringify(rows));
            var data2 = fetchDataFromOtherTable(connection); //returns rows from another table
            console.log(data2); //prints undefined

            res.render('template-page',{data1:data1,data2:data2});
        }          
    }); 

This behaviour is obvious due to the async nature of javascript, and can be solved if I pass data1 to 'fetchDataFromOtherTable' and then render from that function :

 fetchDataFromOtherTable(res,data1,connection);

 /*In fetchDataFromOtherTable */

 data2 = JSON.parse(JSON.stringify(rows));
 res.render('template-page',{data1:data1,data2:data2});

However, for multiple queries, this technique will involve cumulative passing of returned 'rows' at each function call (Also, a lot of function redirects).

Is there a better way to achieve this?

1 Answer 1

1

since NodeJS is asynchronous, you are kind of out of luck doing anything that would work in a large application without using additional modules.

The most popular modules to handle asynchronous calls are async and Q (promises).

Here's an example how to handle asynchronous operations with async:

async.auto({
    get_data: function(callback){
        console.log('in get_data');
        // async code to get some data
        callback(null, 'data', 'converted to array');
    },
    make_folder: function(callback){
        console.log('in make_folder');
        // async code to create a directory to store a file in
        // this is run at the same time as getting the data
        callback(null, 'folder');
    }]
}, function(err, results) {
    console.log('err = ', err);
    console.log('results = ', results);
});

It's fairly straightforward but you'll need to edit your function to run a callback function.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I will give both of them a shot. As i see, these are essentially doing the same thing as redirects, but presented in a more organised way. Any thoughts on performance issues of async and promises though?
There isn't any other solution if you want to do multiple async calls so I would not worry about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.