mojo mojo - 13 days ago 4
Node.js Question

How can i print the result outside the function in express.js?

I have return the function for getting all the parameter documents in express.js .i want to print the result outside the find function.how can get this done help me out

exports.show = function(req, res) {
var parameterObject = [];
var produtObject = [];
Parameter.find().exec(function (err, Parameters) {
if(err) { return handleError(res, err); }
parameterObject.push(Parameters);

});

Product.find().exec(function (err, Products) {
if(err) { return handleError(res, err); }
produtObject.push(Products);

});
console.log(parameterObject);
console.log(produtObject);

}


now console i am getting empty [] object .

Answer

You can't access that outside since Parameter.find() is asynchronous but you can pass a callback which pass the variable parameterObject

exports.show = function(req, res) {
var parameterObject = [];

    function MethodName(callback) {
        Parameter.find().exec(function (err, Parameters) {
            if(err) { return handleError(res, err); }
            parameterObject.push(Parameters);
            return callback(parameterObject);
        });
    }

    MethodName(function(parameterObject) {
        console.log(parameterObject);
    })

}
Comments