我正在尝试构建一个加载请求object
的参数中间件
并将其附加到request object
,这样我就不必一遍又一遍地编写相同的代码。
我使用Sequelize
作为ORM来访问MySQL数据库,这是基于Promise的(bluebird
)。
代码如下:
router.param('id', function (req, res, next, id) {
return models.Object.findById(id)
.then((object) => {
//Check if the requested object was found
if (object) {
//Append the request object to the request object
//for further usage in upcoming route handlers
req.object = object
return next()
} else {
//Throw an error, so that it can be caught
//by the catch block of the promise chain
let err = new Error('Object not found.')
err.status = 404
throw err
}
})
//Catch any error and forward it to the
//next express error handler
.catch((err) => { return next(err) })
})
正如您所看到的,我正在检查请求的对象是否存在以及是否存在,我将它附加到express的请求对象。如果不是我抛出错误。
当我运行此代码时,我收到警告:
Warning: a promise was created in a handler at /*path goes here*/ but was not returned from it
。
在这一点上,我真的不知道如何摆脱这个错误。
我尝试了Hosar的解决方案但不幸的是警告仍然发生。这是我正在使用的确切代码:
router.param('aId', function (req, res, next, aId) {
models.Authorization.findById(aId)
.then((authorization) => {
if (authorization) {
req.authorization = authorization
next()
} else {
let err = new Error('Not Found')
err.status = 404
next(err)
}
})
.catch((err) => { return next(err) })
})
错误发生在我想调用next()而没有任何参数的行上。
完整的警告是:
(node:5504) Warning: a promise was created in a handler at C:\Users\dkaiser
\repos\lead\lead_backend\routes\auth.js:10:16 but was not returned from it
答案 0 :(得分:3)
问题是你要回复一个承诺。只需避免您拥有的第一个返回。
试试:
router.param('id', function (req, res, next, id) {
models.Object.findById(id)
.then((object) => {
//Check if the requested object was found
if (object) {
//Append the request object to the request object
//for further usage in upcoming route handlers
req.object = object
next()
} else {
//Throw an error, so that it can be caught
//by the catch block of the promise chain
let err = new Error('Object not found.')
err.status = 404
next(err);
}
})
//Catch any error and forward it to the
//next express error handler
.catch((err) => { next(err) })
})
答案 1 :(得分:0)
您可以使用Node v7.6中的异步中间件函数直接从已解析的Promise中提取数据
e.Handled = true