NodeJS中如何获取回调函数的返回值
下面的代码使用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
请帮我解决这个问题!
Below is the code uses mongoskin for mongodb access with nodejs.
How do i access the callback function return value from the outside?
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);
I got the error as below,
ReferenceError: ret is not defined
Please help me on this!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是你永远不知道回调何时会触发;它是异步的。因此,您不想等待结果。您应该做的是,您应该调用一个函数,传递该值,而不是返回一个值,并且该函数应该对结果执行您希望它执行的操作。
The problem is you never know when the callback is going to fire; its asynchronous. Therefore you don't want to have anything wait on the result. What you should do is instead of returning a value, you should invoke a function, passing the value, and that function should do what you want it to do with the result.