nodejs function doesnt return a value

Gowtham Raj J

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.

Sal Rahman

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.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Android WebView getContentHeight() doesnt return the correct value

분류에서Dev

NodeJS : How to return value from function if catch error block is hit

분류에서Dev

MySQL num_rows doesnt return value (SELECT INTO)

분류에서Dev

APL return value of a function

분류에서Dev

nodejs cli return [Function : values] for [] .values

분류에서Dev

Onclick function doesnt work

분류에서Dev

Input value doesnt update

분류에서Dev

if Query doesnt not return any data

분류에서Dev

Pass in function or value and always return the value

분류에서Dev

installing nodejs module doesnt give me the command

분류에서Dev

How to get a pointer on the return value of a function?

분류에서Dev

Python: return a default value if function or expression fails

분류에서Dev

Why does a void function return a value?

분류에서Dev

getting address of pointer from function return value

분류에서Dev

Initialize variable as function which return value

분류에서Dev

How to process return value of main() function?

분류에서Dev

return value from function is always undefined and order

분류에서Dev

Coq - return value of type which is equal to function return type

분류에서Dev

My bisection code in python doesnt return the root

분류에서Dev

Google Maps SDK doesnt return directions

분류에서Dev

Return variable doesnt exist in context C#

분류에서Dev

bash function doesnt not work the same as commandline

분류에서Dev

DropDown list doesnt update selected value

분류에서Dev

get function error in c. trying to return string value.

분류에서Dev

No warnings for that function int f() doesn't return any value?

분류에서Dev

method return value call before function runs in program

분류에서Dev

How to import a function with scalar return value in EF 5

분류에서Dev

Php recursive function return null while variable have value

분류에서Dev

How to write function which return types are runtime determined( on the value of argument? )

Related 관련 기사

  1. 1

    Android WebView getContentHeight() doesnt return the correct value

  2. 2

    NodeJS : How to return value from function if catch error block is hit

  3. 3

    MySQL num_rows doesnt return value (SELECT INTO)

  4. 4

    APL return value of a function

  5. 5

    nodejs cli return [Function : values] for [] .values

  6. 6

    Onclick function doesnt work

  7. 7

    Input value doesnt update

  8. 8

    if Query doesnt not return any data

  9. 9

    Pass in function or value and always return the value

  10. 10

    installing nodejs module doesnt give me the command

  11. 11

    How to get a pointer on the return value of a function?

  12. 12

    Python: return a default value if function or expression fails

  13. 13

    Why does a void function return a value?

  14. 14

    getting address of pointer from function return value

  15. 15

    Initialize variable as function which return value

  16. 16

    How to process return value of main() function?

  17. 17

    return value from function is always undefined and order

  18. 18

    Coq - return value of type which is equal to function return type

  19. 19

    My bisection code in python doesnt return the root

  20. 20

    Google Maps SDK doesnt return directions

  21. 21

    Return variable doesnt exist in context C#

  22. 22

    bash function doesnt not work the same as commandline

  23. 23

    DropDown list doesnt update selected value

  24. 24

    get function error in c. trying to return string value.

  25. 25

    No warnings for that function int f() doesn't return any value?

  26. 26

    method return value call before function runs in program

  27. 27

    How to import a function with scalar return value in EF 5

  28. 28

    Php recursive function return null while variable have value

  29. 29

    How to write function which return types are runtime determined( on the value of argument? )

뜨겁다태그

보관