我正在尝试处理(节点:29804)UnhandledPromiseRejectionWarning:test1首先抛出 ,有人知道我该如何处理吗? 在这种情况下,我对使用await不感兴趣。
const test0 = async () => {
try {
throw('test0 first throw');
}
catch(e) {
console.log('test0 last catch');
throw('test0 last throw');
}
}
const test1 = async () => {
try {
test0()
.catch(e => {
console.log('test1 first catch');
throw('test1 first throw'); // This throws unhandled exception
})
// return(0);
}
catch(e) {
console.log('test1 last catch');
throw('test1 last throw');
}
}
const caller = async () => {
try {
let res = test1().
catch(e => {
console.log('PRE FINAL CATCH');
})
console.log(res);
}
catch(e) {
console.log('FINAL CATCH');
// console.log(e);
}
}
caller();
答案 0 :(得分:1)
看到try/catch
和then()/catch()
样式的混合处理承诺很少见。
您可以删除所有不必要的try / catches和return
。不涉及await
。如果其他函数中的某处发生错误,则会记录该错误并将其返回到caller
:
const test0 = async () => {
try {
throw('test0 first throw');
}
catch(e) {
console.log('test0 last catch');
throw('test0 last throw');
}
}
const test1 = async () => {
return test0()
.catch(e => {
console.log('test1 first catch');
throw('test1 first throw'); // This throws unhandled exception
});
}
const caller = async () => {
return test1().catch((e) => {
console.log('PRE FINAL CATCH');
});
}
caller();
如果还有其他要求,我很乐意修改此答案。
答案 1 :(得分:0)
感谢您的回复,我最后在这里进一步了解了异步错误处理的工作原理:https://medium.com/javascript-in-plain-english/javascript-async-function-error-handling-is-not-what-you-think-dac10a98edb2
并最终使用此代码结构。 这个想法对异步和等待的函数具有类似的函数结构和错误处理。 在此示例中,我更喜欢try / catch块的原因是因为它将捕获该函数中可能存在的所有其他错误
//如果无法在调用者函数中使用await,请遵循结构A
/ *************开始结构A ************* /
const handlerFnA = async(fnParam) => { await fnParam(); }
const fnDispatcherA = async () => {
try{
await handlerFnA(innerAsyncFnA);
}
catch (e){
console.log('error caught in fnDispatcher: ', e);
}
}
const innerAsyncFnA = async () => {
try {
throw('I am an error from innerAsyncFn');
}
catch(e) {
console.log('innerAsyncFn catch');
throw(e);
}
}
const callerA = async () => {
try {
fnDispatcherA();
}
catch(e) {
console.log('caller catch');
}
}
/ ***********结束结构A ************ /
//如果可以在调用方函数中使用await,请遵循结构B
/ *************开头结构B ************* /
const handlerFnB = async(fnParam) => { await fnParam(); }
const innerAsyncFnB = async () => {
try {
throw('I am an error from innerAsyncFn');
}
catch(e) {
console.log('innerAsyncFn catch');
throw(e);
}
}
const callerB = async () => {
try {
await handlerFnB(innerAsyncFnB);
}
catch(e) {
console.log('caller catch');
}
}
/ ***********结束结构B ************ /
callerB();