Search code examples
node.jsexpresspg-promise

How do I return my data from a function?


I've written a small database function that gets some data from the DB and puts it into the format that I want, but I'm having difficulties returning the data to display it with Express. The database function is as follows:

function getAllEvents(req, res, next) {
  db.any('select * from sensors, events where sensors.sensorid = events.sensorid')
    .then(function (data) {
        var final = [];

        data.forEach(function(datas){
            if (!final[datas.sensorid]){
                final[datas.sensorid] = {};
            }
            if (!final[datas.sensorid].name){
                final[datas.sensorid].name = datas.name;
                final[datas.sensorid].signatures = {};
            }
            if (!final[datas.sensorid].signatures[datas.signature]){
                final[datas.sensorid].signatures[datas.signature] = {};
                final[datas.sensorid].signatures[datas.signature].id = "sen" + datas.sensorid + "sig" + datas.signature;
                final[datas.sensorid].signatures[datas.signature].signature = datas.signature;
                final[datas.sensorid].signatures[datas.signature].message = datas.message;
                final[datas.sensorid].signatures[datas.signature].events = {};
            }

            final[datas.sensorid].signatures[datas.signature].events[datas.eventid] = datas;
        })

        return final;

    })
    .catch(function (err) {
      console.log("Something went wrong! ", err)
    });
}

And the router function to call it is this:

router.get('/events', function(req, res, next) {
    db.getAllEvents(function(err, data){
        res.render('events', { data: data });
    });
});

I think the router function is waiting indefinitely for the data though as I get no errors but the page never loads. What am I doing wrong?


Solution

  • What am I doing wrong?

    This code:

    router.get('/events', function(req, res, next) {
        db.getAllEvents(function(err, data){
            res.render('events', { data: data });
        });
    });
    

    is ok besides the fact that you are not checking for errors. Notice that getAllEvents is expecting a function as an argument.

    now Let's look at your getAllEvents function prototype

    function getAllEvents(req, res, next) {
    

    It is simply not correct and should have been something like

    function getAllEvents(callback) {
    

    Then you would be able to call the callback and "return" the result like this

    return callback(null,data);
    

    or if an error occurred during you database connection pass the error to the callback

    return callback(err);