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

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

问题描述

我正在使用 nodejs 通过 Mongoose 从 Mongodb 查询数据.获取数据后,我想在响应客户端之前对该数据做一些事情.但我无法获得返回值.在 Google 上查看后,我了解到 Node.js 函数是异步 javascript 函数(非 I/O 阻塞).我试试这个 tut (http://www.youtube.com/watch?v=xDW9bK-9pNY)但它不起作用.下面是我的代码.myObject 在find()"函数内赋值,在find()"函数外未定义.那么我应该怎么做才能获取数据?谢谢!

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');

推荐答案

您得到未定义值的原因是 find 函数是异步的,并且可以随时完成.在您的情况下,它是在您使用 console.log() 后完成的,因此在您访问它们时这些值是未定义的.

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.

要解决此问题,您只能使用 find 函数回调中的值.它看起来像这样:

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天全站免登陆