2014-10-10 32 views
0

我使用node.js和猫鼬进行包括get请求在内的多个HTTP请求。我的get函数将具有相当多的功能,并且可以轻松处理许多数据,我尝试让局部变量存储来自mongo的返回值。例如:保存GET请求返回从node.js和猫鼬变量

router.get('/getstuff/:test', function(req, res) { 
    var testId = req.params.test; 
    var returnStuff = null; 

    var collection = req.collection; 

    collection.find({userIdd : testId}, function(err, data){ 
     if (err) console.log(err); 
     else { 
      console.log(data); // works, data is shown in log 
      returnStuff = data; // does not work, data is not saved to returnStuff 
     } 
    }); 

    console.log(returnStuff); // undefined 
    res.send(); 
}); 

我试图得到什么我从数据库中,数组的returnStuff变回来,但由于关闭,我不能这样做。这可能看起来微不足道,但正如我所说,我会有更多的操作,这将真正简化事情。

任何人有任何提示吗?真的很感激它。

感谢

+0

另请注意“[如何避免Node.js中异步函数的长嵌套](http://stackoverflow.com/questions/4234619/how-to-avoid-long-nesting-of-asynchronous-functions -in-node-js)“ – 2014-10-10 02:22:18

回答

1

collection.find是异步执行的,所以充满returnStuff之前执行res.send。你可以完全摆脱它,只需res.send(数据)在回调中。

这应该工作:

router.get('/getstuff/:test', function(req, res) { 
    var testId = req.params.test; 
    var returnStuff = null; //optional, remove if you don't need it for anything else 

    var collection = req.collection; 

    collection.find({userIdd : testId}, function(err, data){ 
     if (err) console.log(err); 
     else { 
      console.log(data); // works, data is shown in log 
      returnStuff = data; 
      collection.somethingelse(function(err,data2){ 
       returnStuff += data2 
       res.send(returnStuff); 
      });     
     } 
    }); 

}); 

,如果你有很多这样的操作,你可以让他们到图书馆,或使用像异步 退房更多信息这个巨大的资源库:http://book.mixu.net/node/ch7.html

Read this post too, and you'll know EVERYTHING!

+0

问题是,我将在该函数中使用其他mongoose数据库调用,并且会从这些数据中获取更多数据。出于这个原因,我需要访问returnStuff,然后使用我将获得的其他数据。 此外,据我了解(虽然不是很多,我是新的node.js),我只能使用res.send()一次。之后我想返回一个总体结果,就像returnStuff那只是计算的数据。 – intl 2014-10-10 02:10:27

+0

在这种情况下,你将不得不嵌套回调,或者使用类似async的库来同步执行你的操作:看看我在回答中提供的链接 – xShirase 2014-10-10 02:13:16

+0

我使用了嵌套回调。来自Python和C++,node.js是......不同的。 – intl 2014-10-10 05:40:24