Function returns values ​​as undefined in nodejs

This is my first time working on a NodeJs project. And now I'm stuck in a function returning values ​​through JS and getting values ​​to use in express.

var dbitems = "before fn";
function refreshData(callback) {
        db.open(function (err, db) {
            if (!err) {
                db.collection('emp').find().toArray(function (err, items) {
                    dbitems = items;
                    callback(JSON.stringify(items));
                });
            }
            else {
                console.log("Could not be connnected" + err);
                dbitems = {"value":"not found"};
            }
        });

    }
}


refreshData(function (id) { console.log(id); }); 

This function perfectly extracts values ​​from refreshData and writes to the console. But I need to use the resulting value to send the html file from this function to the express using the "returnData" function

exports.index = function (req, res) {
    var valrs = refreshData(function (id) {
        console.log(JSON.parse(id)); ---this again writes data perfectly in the console
    });
    console.log(valrs); -------------------but again resulting in undefined
    res.render('index', { title: 'Express test', returnedData: valrs });
};

Any help would be appreciated.

Thanks and Regards, Luckyy.

+5
source share
1 answer

You need to do this after the database query is completed .. so it must be called from the callback.

exports.index = function (req, res) {
    refreshData(function (id) {
        res.render('index', { title: 'Express test', returnedData: JSON.parse(id) });
    });
};

it's asynchronous, so you can't just put the values ​​in order, you have to go through the callbacks.

+5
source

All Articles