You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在async/await的catch块中获取失败的原始Promise?

如何在async/await的catch块中访问原始Promise?

我正在将部分代码从.then/.catch写法转换为async/await写法,出于日志记录需求,需要在catch块中访问失败的原始Promise。

原始代码:

const myPromise = somePromise()

myPromise.then(() => {
  //...
}).catch((error) => {
  errorLogger(error, myPromise) // 日志工具需要传入原始Promise
})

改用try-catch后遇到作用域问题:

try {
  const myPromise = await somePromise()
  //...
} catch (error) {
  errorLogger(error, myPromise) // myPromise在catch块中不可用
}

解决方案

把原始Promise的声明移到try块外部,让它的作用域覆盖整个try-catch结构:

// 在try外部声明原始Promise
const myPromise = somePromise()
try {
  // 等待Promise完成,如需结果可单独赋值
  const result = await myPromise
  //... 业务逻辑
} catch (error) {
  // 此时myPromise在作用域内,可正常传入日志工具
  errorLogger(error, myPromise)
}

说明

这种写法和原.then/.catch逻辑完全一致:先创建并保存原始Promise实例,再等待它的状态变更。将变量声明移到try外部后,catch块就能访问到这个原始Promise了。如果不需要使用Promise的兑现结果,甚至可以直接写await myPromise而不赋值给额外变量。

内容的提问来源于stack exchange,提问作者Matthew Moran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:32:05