【发布时间】: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(打开控制台)
【问题讨论】:
-
这篇 SO 帖子 stackoverflow.com/questions/45285129/… 为我解决了问题。这与使用多个
awaits 的错误处理有关,而不是使用promise.all()
标签: javascript asynchronous promise