面试题答案
一键面试在JavaScript里使用async/await
时,常见的错误处理方式有以下两种:
使用try...catch块
这是最常用的方式,try
块中放置await
语句,catch
块捕获异步操作抛出的错误。
async function asyncFunction() {
try {
const result = await someAsyncOperation();
console.log(result);
} catch (error) {
console.error('Error occurred:', error);
}
}
在上述代码中,someAsyncOperation
是一个返回Promise的异步函数,如果该Promise被拒绝,catch
块将会捕获到错误并执行相应的处理逻辑。
使用Promise的.catch()方法
将async
函数返回的Promise直接使用.catch()
方法处理错误。
async function asyncFunction() {
return await someAsyncOperation();
}
asyncFunction()
.then(result => console.log(result))
.catch(error => console.error('Error occurred:', error));
这里asyncFunction
执行后返回一个Promise,当someAsyncOperation
抛出错误时,.catch()
块会捕获并处理该错误。