Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a variable that is outside an anonymous function

Tags:

javascript

I have this simple code

 orm: function (req, res) {

    // Send a JSON response


       Noder.query('SELECT * FROM crud ', function(err, results) {
        var all_rows = Noder.query('SELECT count(*) from crud ', function(err, the_rows) {
        return the_rows;
        });

         res.view('noder/orm', {
            layout: 'layout',
            allr:all_rows,
            post:results,
            title: 'This is the hi page title. '
        }); 
      });
   },

which i am using to fetch all rows in a mysql table. However inside that function,i want to have another function that counts how many rows there are in the table.My variable var all_rows shows me undefined when i try displaying it. How can i solve this?.

like image 443
Le Qs Avatar asked Aug 24 '26 18:08

Le Qs


1 Answers

This is because you are accessing the value of all_rows before the inner-query has returned.

Noder.query is an asynchronous function, and as such, its execution will be delayed until the query itself is completed. Meanwhile, your orm function will continue merrily down and call res.view while your inner query is still processing.

To fix this, you can call res.view from inside your inner query.

like image 172
Mike Lawson Avatar answered Aug 27 '26 07:08

Mike Lawson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!