MST

星途 面试题库

面试题:JavaScript 中 async 和 await 的异常捕获基础

在一个使用 async 和 await 的函数中,例如有一个异步操作 await fetch('https://example.com/api').then(response => response.json()),请描述如何捕获该异步操作可能抛出的异常,并写出完整的代码示例。
28.2万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

async 函数中,可以使用 try...catch 块来捕获 await 异步操作抛出的异常。以下是完整代码示例:

async function getData() {
    try {
        const response = await fetch('https://example.com/api');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('捕获到异常:', error);
    }
}

getData();

在上述代码中,try 块包含了需要执行的异步操作,await 会暂停函数执行,直到 fetch 操作完成。如果 fetch 操作或者后续的 response.json() 操作抛出异常,catch 块会捕获到该异常并进行处理。