使用async / await,我尝试了两种不同的语法:
async function asyncFunc() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('promise rejected')
}, 500);
});
}
async function asyncCallWithoutTryCatchBlock() {
await asyncFunc().catch((err) => {
console.log('Catching error');
return;
});
console.log('Outside, after catch is called');
}
async function asyncCallWithTryCatchBlock() {
try {
await asyncFunc();
} catch(err) {
console.log('Catching error');
return;
}
console.log('Outside, after catch is called');
}
asyncCallWithoutTryCatchBlock();
asyncCallWithTryCatchBlock();
I am expecting this output :
Catching error
Catching error
I get this :
Catching error
Outside, after catch is called
Catching error
我想知道为什么在 asyncCallWithoutTryCatchBlock
中调用外部 console.log
,因为我在 catch
块中进行了显式返回?
1 回答
返回在您传递给catch方法的匿名函数内 . 因此,它只从该匿名函数返回 . 作为函数中的最后一个语句,它实际上根本没有用处 .
两个代码片段之间的最大区别在于,一个使用语言构造try catch,另一个使用一个名为catch的方法,它需要一个匿名函数 .