繁体   English   中英

使用等待时使用 catch 处理 Promise 拒绝

[英]Handling Promise rejection with catch while using await

我正在使用await使代码更干净,但我不确定我是否正确处理了异常。

使用 azure-devops-node-api 的示例;

const foo = async() => {
    return new Promise((resolve, reject) => {
        ...
        ...
        const teams = await coreApiObject.getTeams(currProject.id)
                      .catch(err => { reject(err)  return })
        ...
        ...
    })  
}

在这段代码中,我假设,如果 promise 调用有问题,foo() 将返回拒绝。

async函数总是返回 promise,因此您不需要自己显式创建一个。 从异步 function 返回的任何非承诺值都隐式包装在 promise 中。

foo function 内部,您只需要await调用coreApiObject.getTeams(...)并捕获和处理任何错误,使用try-catch块。

您的代码可以简化如下所示:

const foo = async() => {
   try {
      const teams = await coreApiObject.getTeams(currProject.id);
      return teams;
   } catch (e) {
      // handle error
   } 
}

如果您想调用代码来处理错误,那么您可以使用以下选项之一:

  • 删除try-catch块并返回coreApiObject.getTeams(...)的结果。

     const foo = async() => { return coreApiObject.getTeams(currProject.id); }

    Removing the try-catch block and just returning the call to coreApiObject.getTeams(...) will allow the calling code to handle the error because the promise returned by the foo function will get resolved to the promise returned by coreApiObject.getTeams(...) foo coreApiObject.getTeams(...)

    If the promise returned by coreApiObject.getTeams(...) is rejected, promise returned by foo function will also be rejected and hence the calling code will have a change to catch the promise rejection and handle it.

  • catch块中抛出错误。

     const foo = async() => { try { const teams = await coreApiObject.getTeams(currProject.id); return teams; } catch (error) { // throw the error throw error; } }

    您需要从catch块中抛出错误,以确保async function 返回的 promise 被拒绝 如果从catch块返回一个值,则async function 返回的 promise 将使用catch块返回的任何值解析

暂无
暂无

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

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