0

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

chandra
  • 85
  • 2
  • 13
  • You can use `async/await` – Code Maniac Dec 14 '18 at 06:01
  • 1
    You should put res.render inside the "connection.query" block so that when data is returned from the query after that res.render is executed. – Mukul Dev Dec 14 '18 at 06:22
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Patrick Roberts Dec 14 '18 at 06:34

3 Answers3

1
app.post('/result', jsonParser, function(req, res) {
    var sol = []

    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);
        }
      var context= {sol:sol}
      res.render('pages/search',context);
    });
});

query happens asynchronously with your next instructions. So execute the code inside the callback. If .query returns a promise then you can use .then() or async / await.

Also if remove the line res.end as it will end the connection before you can render your page. ( If using async / await )

Prajval M
  • 2,298
  • 11
  • 32
  • I am using two connection query in my code I post only one here – chandra Dec 14 '18 at 07:23
  • Can you be more clear ? Post the code for the whole thing – Prajval M Dec 14 '18 at 07:33
  • I have to run two connection query on two diff datasets. I am getting one array from each query which I need to send in context. above you wrote render in side one connection query then how it will work in my case – chandra Dec 14 '18 at 07:44
0

You can do it with async/await.

app.post('/result', jsonParser, async function(req, res) {
                                ^^^^^ 
    var sol = []
    var val= req.body.typeahead
    let temp = await 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));
    });


  var context={
    sol:sol
}
//Above context going blank

  res.render('pages/search',context);
});
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
-1

You can use to async for it:

sleep = function (ms) {
                    return new Promise(resolve => setTimeout(resolve, ms));
                }

then

while(true){ 
   await sleep(100);
   // do wathever
   if( conditions ){
      break;
    }
}