0

I have this nodejs function, which is for inserting some data into db, and when it finishes inserting it should return 'success' or 'failure'.

This function is in the file insert.js

function insert (req,res) {
    var d = req.body;

    new dbModel({
        name: d.dname,
        desc: d.desc
        }).save(false,function(err){
            if (err){
                return 'failure';
            }else{
                return 'success';   
            }
        });
}

module.exports.insert = insert;

It inserts data into the db, but it doesnt return any value.

This is the route which invokes the above function and this is in the routes.js file.

router.post('/insert', function(req, res) {
    var result = insert.insert(req,res);
    res.render('insert',{title: 'insert',message: result});
});

Am I doing anything wrong or does this have something to do with async nature of nodejs.

Please help. Thanks.

EDIT I tried as @Salehen Rahman said in the answers below, but the page isn't rendering and the browser keeps on waiting for reply from the server and i tried to log the value of result inside the callback function and again no output, it seems the code inside the callback function is not running. I checked the db and data has been inserted successfully.

Gowtham Raj J
  • 937
  • 9
  • 26

1 Answers1

1

That dbModel#save method is asynchronous, and so, the return keyword will only return to the inner the anonymous function. You want to use callbacks, instead. Also remove false from the save method. It can have only callback function as a parameter.

So, your insert function will look like this:

function insert (req, res, callback) {
    var d = req.body;

    new dbModel({
        name: d.dname,
        desc: d.desc
        }).save(function(err){
            if (err){
                // Instead of return, you call the callback
                callback(null, 'failure');
            }else{
                // Instead of return, you call the callback
                callback(null, 'success'); 
            }
        });
}

module.exports.insert = insert;

And your route function will look like this:

router.post('/insert', function(req, res) {
    insert.insert(req, res, function (err, result) {
        res.render('insert',{title: 'insert', message: result});
    });
});

Ideally, though, whenever an inner callback returns an error, you should also call your callback with the error, without any result; absent an error, and at the presence of a successful function call, you set the first parameter to null, and the second parameter to your result.

Typically, the first parameter of the callback call represents an error, where as the second parameter represents your result.

As a reference, you may want to read up on Node.js' callback pattern.

Gowtham Raj J
  • 937
  • 9
  • 26
Sal Rahman
  • 4,607
  • 2
  • 30
  • 43