Umer
Umer

Reputation: 43

Can't access variable declared inside connection.query function

I am getting result from query and storing it in a variable which i will send through render but the problem it is giving error variable is not defined. Please help me out. Do correct the code if possible please.

router.get('/create',(req,res)=>{

        connection.query('SELECT * FROM purchases',function(error,results,fields){

            var voucher = 'PH-'+results.length+1;
            connection.query('SELECT * FROM vendors where wid=?',[req.session.w_id],function(err,res,f){
                var vendors=res;
                connection.query('SELECT * FROM products where wid=?',[req.session.w_id],function(er,r,fi){
                    var products=r;


                })
            })

        });

        res.render('purchase_create',{voucher:voucher,vendors:vendors,products:products});  

});

Error is: voucher is not defined

Upvotes: 0

Views: 107

Answers (2)

Shivani Sonagara
Shivani Sonagara

Reputation: 1307

The ‘query’ method of the connection object requires a callback function which will be executed whenever either one of the three events fires – error, fields, results, here denoted by the parameters err, fields and rows respectively.

router.get('/create', (req, res) => {
  connection.query('SELECT * FROM purchases', function (error, results, fields) 
  {
    if (error) throw error;

    var voucher = 'PH-' + results.length + 1;
    connection.query('SELECT * FROM vendors where wid=?', [req.session.w_id], function (err, res, f) 
    {
         if (err) throw err;
         var vendors = res;
         connection.query('SELECT * FROM products where wid=?', [req.session.w_id], function (er, r, fi) 
         {
             if (er) throw er;
             var products = r;
             res.render('purchase_create', { voucher: voucher, vendors: vendors, products: products });
        });
     });
  });
});

Upvotes: 0

Niklas Higi
Niklas Higi

Reputation: 2309

voucher is only available inside the callback function you're passing to connection.query, same thing with the vendors and products. You'll have to move the res.render call into the inner-most function to make this work:

router.get('/create', (req, res) => {
  connection.query('SELECT * FROM purchases', function (error, results, fields) {
    var voucher = 'PH-' + results.length + 1;
    connection.query('SELECT * FROM vendors where wid=?', [req.session.w_id], function (err, res, f) {
      var vendors = res;
      connection.query('SELECT * FROM products where wid=?', [req.session.w_id], function (er, r, fi) {
        var products = r;

        res.render('purchase_create', { voucher: voucher, vendors: vendors, products: products });
      });
    });
  });
});

Upvotes: 1

Related Questions