Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we return string from callback function to root function in node.js?

function add(post)
{
    var word = new KeyWord({ keyword: post.keyword});    
    word.save(function (err, word) 
    {
        if(err)
        {
            if(err.code==11000)
                return post.keyword + ' is already added.';
        }
        else
            return 'Added : ' + post.keyword;
    });
}

When I am trying to read return value of add function it returns nothing.
And also when I am trying to put message in variable and return that from outside also give null value.

like image 929
Devang Bhagdev Avatar asked Jan 12 '23 02:01

Devang Bhagdev


1 Answers

To put it simply, you can't. To get values from functions like these, you must use a callback:

function add(post, callback) {
  var word = new KeyWord({keyword: post.keyword});    
  word.save(function(err, word) {
    if (err) {
      if (err.code==11000) callback(post.keyword + ' is already added.');
      else callback('Added : ' + post.keyword);
    }
  });
}

You'd then use the function like this:

add(post, function(result) {
  // return value is here
}
like image 195
hexacyanide Avatar answered Jan 24 '23 07:01

hexacyanide