在异步的NodeJS函数的返回值 [英] return value from asynchronous function in Nodejs

查看:164
本文介绍了在异步的NodeJS函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的NodeJS查询数据MongoDB的throught猫鼬。
得到数据后,我希望它响应客户端之前完成对这些数据的东西。但我不能得到返回值。寻找在谷歌之后,我已经学会了Node.js的功能是异步javascript函数(非I / O块)。我试试这个啧啧( http://www.youtube.com/watch?v=xDW9bK- 9pNY ),但它不工作。下面是我的code。该myObject的被重视内部查找()函数和不确定的外部找到()函数。所以,我应该怎么做来获得数据?谢谢!

 变种人= mongoose.model('人',PersonSchema);
变种产品= mongoose.model(产品,ProductSchema);
VAR myObject的=新的对象();Person.find的()。EXEC(函数(ERR,文档){
    对于(VAR I = 0; I< docs.length;我++)
    {
    Product.find({用户:文档[I] ._ ID},功能(呃,个人){
    myObject的[I] =个人;
    的console.log(myObject的[I]); //返回值是确定
    });
    的console.log(myObject的[I]); //返回未定义值
    }
    的console.log(myObject的); //返回未定义值
});
    的console.log(myObject的); //返回未定义值app.listen(3000);
的console.log('侦听端口3000');


解决方案

你得到未定义值的原因是因为查找功能是异步的,并且可以随时结束。在你的情况下,你使用后的console.log(),所以值是当你访问这些不确定的整理。

要解决这个问题,你只能使用查找功能的回调里面的值。它看起来是这样的:

 变种人= mongoose.model('人',PersonSchema);
变种产品= mongoose.model(产品,ProductSchema);
VAR myObject的=新的对象();函数的getData(文档,回调){
  功能循环(ⅰ){
    Product.find({用户:文档[I] ._ ID},功能(呃,个人){
      myObject的[I] =个人;      如果(ⅰ&下; docs.length){
        循环第(i + 1);
      }其他{
        回电话();
      }
    });
  };
  环(0);
};Person.find的()。EXEC(函数(ERR,文档){
  的getData(文档,函数(){
    // myObject的已被填充在这一点上
  });
});

的数据处理已被移动到一个循环等待previous迭代来完成。通过这种方式,我们可以判断当最后一个回调,以火在包装函数的回调已经解雇了。

I am using nodejs to query data from Mongodb throught Mongoose. After get the data, I want do something on that data before responding it to client. But I can not get the return-value. After looking on Google, I have learned Node.js functions is asynchronous javascript function (non I/O blocking). I try this tut (http://www.youtube.com/watch?v=xDW9bK-9pNY) but it is not work. Below is my code. The myObject is valued inside "find()" function and undefined outside "find()" function. So what should I do to get the data? Thanks!

var Person = mongoose.model('Person', PersonSchema);
var Product = mongoose.model('Product', ProductSchema);
var myObject = new Object();

Person.find().exec(function (err, docs) {
    for (var i=0;i<docs.length;i++)
    { 
    Product.find({ user: docs[i]._id},function (err, pers) {
    myObject[i] = pers;
    console.log(myObject[i]); //return the value is ok
    });
    console.log(myObject[i]); //return undefined value
    }
    console.log(myObject); //return undefined value
});
    console.log(myObject); //return undefined value

app.listen(3000);
console.log('Listening on port 3000');

解决方案

The reason you're getting undefined values is because the find function is asynchronous, and can finish at any time. In your case, it is finishing after you're using console.log(), so the values are undefined when you're accessing them.

To fix this problem, you can only use the values inside the find function's callback. It would look something like this:

var Person = mongoose.model('Person', PersonSchema);
var Product = mongoose.model('Product', ProductSchema);
var myObject = new Object();

function getData(docs, callback) {
  function loop(i) {
    Product.find({ user: docs[i]._id}, function (err, pers) {
      myObject[i] = pers;

      if (i < docs.length) {
        loop(i + 1);
      } else {
        callback();
      }
    });
  };
  loop(0);
};

Person.find().exec(function(err, docs) {
  getData(docs, function() {
    // myObject has been populated at this point
  });
});

The data processing has been moved to a loop that waits for the previous iteration to complete. This way, we can determine when the last callback has fired in order to fire the callback in the wrapper function.

这篇关于在异步的NodeJS函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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