【问题标题】:How to get the callback function return values in NodeJSNodeJS如何获取回调函数的返回值
【发布时间】:2011-11-13 00:14:17
【问题描述】:

下面是使用 mongoskin 通过 nodejs 访问 mongodb 的代码。 如何从外部访问回调函数返回值?

app.get('/', function(req, res) {

    var ret = db.collection('counters').findAndModify(
        {_id: 'messagetransaction'},
        [],
        {$inc : {next: 1}},
        true,
        true,
        function(err, counter) {
            if (err) { 
                throw err;
            }else{
                console.log(counter.next);
                return counter.next;
            }       
        }
    );

});


console.log(ret);

我得到如下错误,

ReferenceError: ret is not defined

请帮帮我!

【问题讨论】:

    标签: mongodb node.js mongoose


    【解决方案1】:

    问题是你永远不知道回调什么时候触发;它的异步。因此,您不想等待任何结果。您应该做的不是返回一个值,而是调用一个函数,传递该值,并且该函数应该执行您希望它对结果执行的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2019-07-25
      • 2021-06-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      相关资源
      最近更新 更多