【问题标题】:Error thrown in awaited Promise not caught in catch block [duplicate]在等待的 Promise 中抛出的错误未在 catch 块中捕获 [重复]
【发布时间】:2020-11-20 07:57:09
【问题描述】:

我在 try/catch 块中有 2 个 promise,之后还有第三个函数使用等待的响应。

当我在lastFunction的参数中awaitres1和res2时,抛出的错误没有被catch块捕获。

当我通过const res2 = await promise2() 正常等待它们时,错误被捕获在 catch 块中。

为什么会这样?

const handler = async () => {
  const results = await Promise.all(
    [1].map(async id => {
      try {
        const res1 = promise1()        
        const res2 = promise2() 
        const finalResponse = await lastFunction(await res1, await res2)
      } catch (err) {
        console.log('Catching error')
        console.log(err)
      }
    })
  )
}

const promise1 = () => {
  return new Promise((res, rej) => {
    setTimeout(() => res(1), 1000)
  })
}

const promise2 = () => {
  return new Promise((res, rej) => {
    throw new Error('second one broke')
  })
}

const lastFunction = (prom1, prom2) => {
   return new Promise((res, rej) => {
     res('done')
   })
}

handler();

CodePen:https://codepen.io/OliverNural/pen/oNbrMWw(打开控制台)

【问题讨论】:

标签: javascript asynchronous promise


【解决方案1】:

promise2 抛出错误,而不是拒绝承诺。不管你在哪里 await 它,它仍然不会捕获错误,因为错误源于承诺。如果您更改 promise2 以正确拒绝承诺(rej("second one broke") 而不是 throw new Error("second one broke")),那么您会注意到 catch 确实有效。

【讨论】:

  • 恐怕如果我将await 放在函数调用之前,它确实会正确捕获它。你可以用上面这样的笔来测试这个变化。
  • 我有,但没有发现错误。
  • 嗯,我的错。我无法像我想的那样在 Codepen 中复制它。有些不同,我会看看我的代码和你的建议。
  • "错误源自承诺" - 澄清一下,我想说错误是从setTimeout 回调中抛出的,而不是 来自承诺。承诺完全不受影响,它没有被拒绝。
  • 在某些情况下,我使用 catch 是因为我在 promise1()promise2() 中进行 HTTP 调用,并且我将错误处理交给调用者处理。那么也许Bergi很接近?抱歉,之前没想到有关系。
猜你喜欢
  • 2019-02-11
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2018-04-20
  • 2016-05-22
  • 2017-06-20
  • 2021-01-12
  • 1970-01-01
相关资源
最近更新 更多