【问题标题】:connect to server api page连接到服务器 api 页面
【发布时间】:2021-11-11 02:47:51
【问题描述】:

通过在没有 catch 块的情况下抛出异步函数,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 cli 标志 --unhandled-rejections=strict(请参阅 [

const router = require("express").Router();
const User = require("../modles/User");


router.get("/register", async (req,res) => {
   
    const user = await new User({
    username:"jhon",
       email:"jhon@gmail.com",
       password:"123456",
    
    
   })

   await user.save()
   res.send("ok")
   
});

module.exports = router;

]1 (rejection id: 1) (node:13400) [dep0018] deprecationwarning: 不推荐使用未处理的 Promise 拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 node.js 进程。

【问题讨论】:

  • 将代码封装在try-catch 块中的路由处理函数中。此外,您不需要await new User(....)await 仅在 user.save() 之前需要

标签: javascript async-await try-catch


【解决方案1】:

你只需要一个 await 和一个 catch。第一个没用,因为你初始化了你的类。

那就这样做吧:

const router = require("express").Router();
const User = require("../modles/User");


router.get("/register", async (req,res) => {
   
    const user = new User({
    username:"jhon",
       email:"jhon@gmail.com",
       password:"123456",
   })

   await user.save().catch(e => e) // Return the errors in the void. You can console.log it.
   res.send("ok")
   
});

module.exports = router;

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2011-08-06
    • 2017-01-27
    • 2020-12-13
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多