我们如何将字符串从回调函数返回到 node.js 中的根函数? [英] How can we return string from callback function to root function in node.js?

查看:17
本文介绍了我们如何将字符串从回调函数返回到 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;
    });
}

当我试图读取 add 函数的返回值时,它什么都不返回.
而且当我尝试将消息放入变量并从外部返回时也会给出空值.

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.

推荐答案

简单地说,你不能.要从这些函数中获取值,您必须使用回调:

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
}

这篇关于我们如何将字符串从回调函数返回到 node.js 中的根函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆