我想重用我的控制器来处理数据库操作。我有点困难于构建我的应用程序。下面是我有:如何重用数据库控制器
server.js
var apiController = require('./controllers/api');
router.get('/cars', function (req, res) {
// get all cars from DB and render view
apiController.getCars().then(function (cars) {
res.render('index', {cars: cars});
});
});
router.get('/api/cars', function (req, res) {
// get all cars from DB and return JSON
apiController.getCars().then(function (cars) {
res.json(cars);
});
});
控制器/ api.js
module.exports = {
getCars: function() {
db.collection('cars').find().toArray(function (err, cars) {
if (err) throw err;
return cars;
});
},
// tried also something like this but this doesn't really work
// for my use case because I don't want to attach any particular
// res to the function
getCars: function (req, res, next) {
db.collection('cars').find().toArray(function (err, cars) {
if (err) throw err;
res.json(cars);
});
},
};
感谢您的回答,您是对的,我期待server.js的承诺,这就是为什么它没有工作。使用承诺标准方式处理DB控制器 - 路由器关系中的表达?我基本上在寻找正确的模式,我不一定会遵守承诺。 – finspin
这种方法的一个缺点是我不得不在每个路由器上对getCars进行错误处理,对吧? – finspin
回调是在JavaScript中处理异步的旧方法。承诺新的。所以我建议你使用Promise,如果你不觉得太紧张的话。 –