使用 CouchDB 和 nano.js 进行回调和返回
我正在尝试使用 nano 编写一个带有可重用数据库调用的小型库。
db.view('list', 'people', function(error, data) {
if (error == null) {
res.render('people/index', {
people: data.rows
});
} else {
// error
}
});
当有多个请求时,这可能会变得非常混乱:
db.view('list', 'people', function(error, people) {
db.view('list', 'items', function(error, items) {
db.view('list', 'questions', function(error, questions) {
db.view('list', 'answers', function(error, answers) {
...
res.render('people/index', {
people: people.rows,
items: items.rows,
questions: questions.rows
...
所以,我们的想法是创建一个函数:
var getPeople = function() {
// do db calls here and return
}
res.render('people/index', {
people: getPeople()
});
但这不起作用。
我该如何解决这个问题并将所有内容放入外部 node-js-module.js 文件中?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用 caolan 的 aysnc 库。非常容易使用,它可以在浏览器和沙发上使用 require (不是你将在沙发侧使用来查询)。
对于特定问题,您可以使用系列或瀑布:
I would suggest caolan's aysnc library. Very easy to use, and it works on both browser and in couch with require (not that you will be using on the couch side to query).
For the particular problem you can use series or waterfall:
您是否考虑过在 CouchDB 中查看视图整理?这将帮助您减少 db.view(..) 调用次数并在 1 个视图查询中返回所需的所有数据。对于单个一对多(即“人”有许多“项目”)来说非常容易。对于多个级别来说可能需要更多的努力,但它应该以相同的方式工作。这里有一些关于 Couch 视图整理的好文章:
CouchDB Joins
CouchDB 查看排序规则
Have you considered view collation of your views in CouchDB? This would help you to reduce the number of db.view(..) calls and return all the data you need in 1 view query. It's pretty easy for a single one-to-many (ie; 'person' has many 'items'). It maybe a little more effort for multiple levels, but it should work the same way. There are some good articles on Couch view collation here:
CouchDB Joins
CouchDB View Collation
我知道的最好的解决方案是使用 承诺。需要一点时间来适应,但这是值得的。我正在使用 Kris Kowal 的 Q 库。他在 JSConf-2010 上很好地演练了 Q API 和设计(跳转至 15:30)。
The best solution I know of, is to use promises. It takes a little bit to get used to, but it's well worth the effort. I'm using Kris Kowal's Q-library. He gave a good walk-through of the Q API's and design at JSConf-2010 (jump to 15:30).
您已经在这里得到了一些很好的答案。
从纳米源代码中,您有一个可能有帮助的示例:
另外,如果您不太了解 NodeJS 流控制的工作原理,我强烈推荐您查看本教程:
比使用工具更好的方法是使用该工具并了解其工作原理:) 也许您最终只会编写自己的控制流,这就是我们大多数人最终所做的事情。
希望这有帮助,为了方便起见附上代码。
You got some great answers here already.
From the nano source code you have an example that might help:
Also if you don't really understand how nodejs flow control works I can't recommend enough that you see this tutorial:
Better than using a tool is to use the tool understanding how it works :) Maybe you'll end up just coding your own control flow, that's what most of us ends up doing anyway.
Hope this helps, attached code for convenience.