首页 > 解决方案 > 使用 then-catch 的 try-catch 中的 Node.js 问题

问题描述

我写了一个 try-catch 函数,在 try 中,我执行然后 catch 承诺。我想把错误扔给try-catch,catch。我不知道该怎么解释。请查看我的代码,您将在这里理解问题:

try {
  function().then(result =>{
    if(result){
      // do something
      function2().then(result =>{
        if(result){
        // do something
        }else{
        throw "bad request";
        }
       }).catch((error)=>{
        throw error
       })
    }else{
      throw "not found";
    }
  }).catch(error =>{
    throw error
  });
}catch (error){
  callback(BAD_REQUEST);
}

我可以这样做还是不这样做,还是有其他方法可以做到这一点?

标签: javascriptnode.jsecmascript-6try-catches6-promise

解决方案


.then接收回调函数。要捕获错误,您必须将 try-catch 放入 .then 回调中。

该怎么办?

要捕获 Promise 的错误,您可以使用.catch()或使用现代 async/await。


推荐阅读