【问题标题】:My NodeJs gives error for unhandledPromise我的 Node Js 为未处理的 Promise 提供错误
【发布时间】:2021-01-23 14:12:24
【问题描述】:

exports.createTour = async (req, res) => {
  try {
    const newTour = await Tour.create(req.body);
    res.status(201).json({
      status: "success",
      data: {
        tours: newTour,
      },
    });
  } catch (err) {
    res.status(400).json({
      status: "fail",
      message: err,
    });
  }
};

在我在这里添加异步功能之前,一切都在运行。可能是什么原因?

【问题讨论】:

  • .json 方法是否同步? catch 语句中是否抛出异常?

标签: javascript node.js postman atom-editor nodemon


【解决方案1】:

Tour.create 内部发生了什么?

难道你是在 new Promise((resolve,reject){...}) 中调用 Promise.reject() 而不是使用 reject()

下一个代码用于我的“bla”函数中的拒绝和解决案例:

exports.createTour = async (req, res) => {
      try {
        const newTour = await bla();
        res.status(201).json({
          status: "success",
          data: {
            tours: newTour,
          },
        });
      } catch (err) {
        res.status(400).json({
          status: "fail",
          message: err,
        });
      }
});

    
    let bla=()=>{
      return new Promise((resolve, reject)=>{
        //resolve("yay");
        reject("I have my reasons");
      });
    }

我会试着解释我怀疑发生了什么—— 但是不看代码就很难知道:

let create = ()=>{
      // option 1. returns a new promise that resolves - your catch should work 
      Promise.resolve("great success");

      return new Promise((resolve, reject)=>{
        // option 2. creates a new promise in the new promise, which would explain the situation you described
        Promise.reject("I need to be handled too - but im not");

        // option 3. handles the locally created and rejected promise
        Promise.reject("I need to be handled too").catch(x => console.log("handled"));

        // option 4. rejects and is caught in the createTour function that called us - your catch should work  
        reject("I have my reasons");

       // option 5. another function you call rejects and is not handled - would also cause what you described, for the same reason
       let result = await func();
      });
    }

尝试看看你是否有某种选项 5 或 2 正在进行 - 它在承诺中创建一个承诺,拒绝(并且不被处理)..

另外,请注意,您可以在代码周围使用完整的 try{..}catch{..},而不是使用

await Tour.create().catch(err => ...);

(如选项 2)并专门处理拒绝

如果您想了解更多信息: https://blog.bitsrc.io/6-ways-to-implement-a-promise-in-javascript-9238aec9c17b

【讨论】:

  • bla 函数是用户定义的,create 是预定义的,这有什么区别吗?
  • Tour.create 在哪里以及如何定义?我以为它在你的代码中..如果它只是在另一个文件中,它应该没有区别
  • 我进行了编辑以显示可能导致拒绝的不同方式以及根据您发布的内容我认为正在发生的事情。可能是内部创建您调用另一个方法返回拒绝而不处理它..
  • createTour 之前有一个函数,导致问题,所以我不得不删除它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 2014-08-22
  • 2020-12-11
  • 2012-05-24
  • 2016-05-08
相关资源
最近更新 更多