4

I am working on a NodeJs project for the first time. And now i am stuck with the 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 retrieves values perfectly from refreshData and writes into console. But what I need is to use the retrieved value to send into express html file from this function by "returnedData"

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 & Regards, Luckyy.

1 Answer 1

5

You need to render this after the database request finishes.. so it needs to be called from within 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 values in order, needs to go through the callbacks.

Sign up to request clarification or add additional context in comments.

1 Comment

There you go, thanks Agreco. To the point answer and so highly appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.