在 promise 链中调用 express 中间件的 next() 方法

3

我正在尝试构建一个参数中间件,它会加载请求的object并将其附加到request对象上,这样我就不必反复编写相同的代码了。 我正在使用ORM来访问MySQL数据库,所选ORM是基于Promise的(bluebird),具体而言是Sequelize。 下面是示例代码:

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) 警告:在C:\Users\dkaiser\repos\lead\lead_backend\routes\auth.js的第10行16列处的处理程序中创建了一个promise,但未从其中返回。


有人有解决这个问题的方案吗? - NIKHIL C M
2个回答

3
问题在于你返回了一个 Promise。只需避免第一个 return 即可。
尝试:
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) })
})

0

您可以使用来自Node v7.6的异步中间件函数直接从已解决的Promise中提取数据。

router.param('id', async function (req, res, next, id) {
  const object = await models.Object.findById(id);
  if (object) {
    req.object = object;
    next();
  } else {
    let err = new Error('Object not found.')
    err.status = 404
    next(err);
  }
 });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接