I am trying to do simple search in MySQL database in node js and want to send searched result on template.
app.post('/result', jsonParser, function(req, res) {
var sol = []
var ins= []
var val= req.body.typeahead
connection.query('SELECT Sol_name from solutions where Sol_name like "%'+val+'%"', function(err, rows, fields) {
if (err) throw err;
for(i=0;i<rows.length;i++)
{
sol.push(rows[i].Sol_name);
}
res.end(JSON.stringify(sol));
});
connection.query('SELECT ins_name from installtions where ins_name like "%'+val+'%"', function(err, rows, fields) {
if (err) throw err;
for(i=0;i<rows.length;i++)
{
ins.push(rows[i].ins_name);
}
res.end(JSON.stringify(ins));
});
var context={
sol:sol,
ins:ins
}
//Above context going blank
res.render('pages/search',context);
});
Now problem is that, when I am executing this code it is sending blank sol and ins array because it is not waiting for completing the fetching from database part.
This is due to node js asynchronous feature. how can I solve this issue
I also try sleep before render to template but sleep is not working in node js.
Please help