简体   繁体   English

Expess 中的 UnhandledPromiseRejectionWarning 错误

[英]UnhandledPromiseRejectionWarning error in Expess

const Car = mongoose.model('Car', new mongoose.Schema({
  name: {
    type: String,
    required: true,
  }
}));


router.put('/:id', async (req, res) => {
  const { error } = joiValidator(req.body); 
  if (error) return res.status(400).send(error.details[0].message)

  try {
    const car= await Car.findByIdAndUpdate(req.params.id, { name: req.body.name }, {new: true })
  } catch (error) {
    return res.status(404).send('not found.');
  }  
  
  res.send(car);
})

i am successfully connected to mongoDB using mongoose, its only when i try to mock an error by giving a wrong id as an input i get the following error, even though i handled async and await with the trycatch block我使用 mongoose 成功连接到 mongoDB,只有当我尝试通过将错误的 id 作为输入来模拟错误时,我才会收到以下错误,即使我处理了 async 并使用 trycatch 块等待

(node:19392) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19392) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

This is mainly because you are using try an catch after an if.这主要是因为您在 if 之后使用了 try 和 catch。 In javascript the way of reading code is asynchronous so, if and try are executed at the same time.在 javascript 中,读取代码的方式是异步的,因此 if 和 try 是同时执行的。 Also, you don´t need to use an async function here, as you are only calling one promise.此外,您不需要在这里使用异步函数,因为您只调用了一个 promise。

Here I let you a simpler code without async.在这里我让你一个更简单的代码没有异步。

router.put("/:id", (req, res) => {
  const { error } = joiValidator(req.body);
  if (error) {
    return res.status(400).send(error.details[0].message);
  } else {
    Car.findByIdAndUpdate(req.params.id,{ name: req.body.name },{ new: true },(err, car) => {
        if (err) return res.status(404).send({ message: 'Not found', err });
        return res.status(200).send(car);
      }
    );
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM