【发布时间】:2018-04-11 12:26:03
【问题描述】:
路由器:
router.get('/available', VehicleController.getAvailable)
router.put('/:vin/current-location', validate(vehicleValidation.currentLocation), VehicleController.saveCurrentLocation)
控制器
class VehicleController {
async getAvailable (req, res, next) {
try {
res.json(await VehicleQueries.getAvailable())
} catch (e) {
next(e)
}
}
async saveCurrentLocation (req, res, next) {
try {
res.json(await VehicleQueries.updateLocation(req.params.vin, req.body.lng, req.body.lat))
} catch (e) {
next(e)
}
}... etc etc
以上是使用新的 async 和 await 构建在 nodejs 中的简单 crud 应用程序。每条路由都会验证输入,然后传递给控制器。上面的示例调用另一个类中的方法,其中包含查询,而查询又返回一个承诺。
如您所见,我必须将每个控制器的代码包装在 try and catch 中。这变得相当烦人,我认为必须有一种更清洁的方法。
是否有可能以某种方式将控制器方法本身包装在 try catch 中?这样我可以将控制器简化为:
class VehicleController {
async getAvailable (req, res, next) {
res.json(await VehicleQueries.getAvailable())
}
async saveCurrentLocation (req, res, next) {
res.json(await VehicleQueries.updateLocation(req.params.vin, req.body.lng, req.body.lat))
}... etc etc
【问题讨论】:
标签: javascript node.js asynchronous