[英]How can I catch error rethrown from async function?
try {
const promise = new Promise(async (resolve, reject) => {
reject('oe')
})
.catch(async (err) => {
console.log('bbbbb', err)
throw err
})
} catch (err) {
console.log('aaaaa', err)
}
Is is possible to make aaaaa
loggable 有可能使aaaaa
In general, it doesn't make sense to pass an async
function into a promise's then
or catch
function. 通常,将async
函数传递到async
的then
或catch
函数没有任何意义。 And it never makes sense to pass one into the promise constructor. 而且,将一个传递给promise构造器也没有任何意义。 If you're going to go async
, do it earlier. 如果您要async
,请async
进行。 Also, when you want a rejected promise for testing, etc., just use Promise.reject('oe')
. 另外,当您想要拒绝测试的承诺等时,只需使用Promise.reject('oe')
。
In order to catch an error from an async
function with a try
/ catch
, you must be in an async
function. 为了使用try
/ catch
从async
函数中捕获错误,您必须处于async
函数中。 In that case, the minimal change to your example would be to await
the result of the call to catch
: 在这种情况下,对示例的最小更改是await
catch
的调用结果:
// Assuming this is in an `async` function, making only minimal changes
try {
const promise = new Promise(async (resolve, reject) => {
reject('oe')
})
.catch(async (err) => {
console.log('bbbbb', err)
throw err
})
await promise; // ***
} catch (err) {
console.log('aaaaa', err)
}
If you aren't in an async
function, you can't use try
/ catch
to catch errors from promises (which includes from an async
function call, since they return promises). 如果您不在async
函数中,则不能使用try
/ catch
来捕获来自promise的错误(包括来自async
函数调用的错误,因为它们会返回promise)。 Instead, you have to use the promise returned by catch
: 相反,您必须使用catch
返回的promise:
// Assuming this is NOT in an `async` function, making only minimal changes
const promise = new Promise(async (resolve, reject) => {
reject('oe')
})
.catch(async (err) => {
console.log('bbbbb', err)
throw err
})
.catch(err => {
console.log('aaaaa', err)
})
Making larger changes, if you're already in an async
function, get rid of the then
and catch
calls: 进行较大的更改,如果您已经在async
函数中,请除去then
并catch
调用:
// Assuming this is in an `async` function
try {
try {
await Promise.reject('oe');
} catch (innerError) {
console.log('bbbbb', innerError);
throw innerError;
}
} catch (outerError) {
console.log('aaaaa', outerError);
}
You can use async/await
: 您可以使用async/await
:
async function test() { try { const promise = await new Promise(async (resolve, reject) => { reject('oe') }).catch(async err => { console.log('bbbbb', err) throw err }) } catch (err) { console.log('aaaaa', err) } } test()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.