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

后端 未结 1 1772
难免孤独
难免孤独 2020-12-11 20:35
function add(post)
{
    var word = new KeyWord({ keyword: post.keyword});    
    word.save(function (err, word) 
    {
        if(err)
        {
            if(err         


        
相关标签:
1条回答
  • 2020-12-11 20:50

    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
    }
    
    0 讨论(0)
提交回复
热议问题