-1

I'm trying to return some rows from a db, connection works fine and everything but when express calls the function that retrieves the data it doesn't wait for the response.

I've tried many ways to write a callback to no avail, I've even tried using async (see code below), and it still runs all the way to the end before the data is even there. Any help?

router.get('/db/selectAllReadings', function(req, res) {
  async.waterfall([
    function(next){
      console.log('function 1');
      var rows = dbFunctions.selectAllReadings();
      next(rows);
    },
    function(next, rows){
      console.log('function 2');
      console.log(rows);
      next(rows);
    },
    function(next, rows){
      console.log('function 3');
      res.json(rows);
    }
  ]);
});
Artemio Ramirez
  • 1,116
  • 1
  • 10
  • 23

2 Answers2

0

I finally managed it to work, thanks to @imran khan for helping me see things clearer.

router.get('/db/selectAllReadings', function(req, res) {
  dbFunctions.selectAllReadings(function(rows){
    res.json(rows);
  });
});
Artemio Ramirez
  • 1,116
  • 1
  • 10
  • 23
-1
router.get('/db/selectAllReadings', function(req, res) {
  async.waterfall([
    function(next){
      console.log('function 1');
      dbFunctions.selectAllReadings(function(err,data){
        if(err){
        }else{
          var rows = data;
          next(rows);
        }
      });

    },
    function(next, rows){
      console.log('function 2');
      console.log(rows);
      next(rows);
    },
    function(next, rows){
      console.log('function 3');
      res.json(rows);
    }
  ]);
});

//need to do little bit change in your dbFunction

if (err) {
            callback(err,null);
        }
        else if (data.length > 0) {
            callback(null,data);
        }

i hope u will get an better idea of it..

imran khan
  • 474
  • 5
  • 10