【发布时间】:2014-05-08 01:04:21
【问题描述】:
假设我有以下 Express/Connect 中间件:
return function(req, res, next) {
mongoose.connect(url, options);
var Config = mongoose.model('Config', mongoose.Schema({
field1: Boolean,
field2: []
}));
Config.findOne({}, function (err, doc) {
if(!err) {
if(someCondition)
// some logic: send response and interrupt middleware chain
res.end('Some response');
else
next();
}
}
};
问题是数据库调用是异步的。所以中间件函数在任何逻辑执行之前退出。 任务很简单:从 mongoDB 读取配置,如果某个字段值 = 'something" 发送响应,否则 - 继续中间件链。
所以,我现在有 2 个问题:
- 有没有办法在中间件内部进行异步调用?
- 如果没有,是否有任何解决方法? (AFAIK,没有办法同步执行 db 调用)
【问题讨论】:
标签: node.js mongodb asynchronous express middleware