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

13,026

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
}
Share:
13,026
Devang Bhagdev
Author by

Devang Bhagdev

Updated on June 15, 2022

Comments

  • Devang Bhagdev
    Devang Bhagdev about 2 years
    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.