测验

如何处理异步操作中的错误?

主题
异步JavaScript
在GitHub上编辑

TL;DR

要处理异步操作中的错误,可以使用带有 async/await 语法的 try...catch 块或带有 Promises 的 .catch() 方法。例如,使用 async/await,您可以将代码包装在 try...catch 块中以捕获任何错误:

async function fetchData() {
try {
// Invalid URl
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData(); // Error fetching data: ....

使用 Promises,您可以使用 .catch() 方法:

fetch('https://api.example.com/data') // Invalid URl
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error fetching data:', error));

使用 try...catchasync/await

基本用法

使用 async/await 时,您可以通过将异步代码包装在 try...catch 块中来处理错误。这允许您捕获在执行 await 语句期间发生的任何错误。

async function fetchData() {
try {
// Invalid URl
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData(); // Error fetching data: ....

嵌套异步操作

如果您有多个异步操作,则可以嵌套 try...catch 块以处理不同级别的错误。

async function fetchUser() {
// Simulate a successful async operation
return { id: 1, name: 'Alice' };
}
async function fetchUserPosts() {
// Simulate a failed async operation
throw new Error('Failed to fetch posts');
}
async function loadUserData() {
try {
const user = await fetchUser();
console.log('User:', user);
try {
const posts = await fetchUserPosts();
console.log('Posts:', posts);
} catch (postsError) {
console.error('Error fetching posts:', postsError.message);
}
} catch (userError) {
console.error('Error fetching user:', userError.message);
}
}
loadUserData();

使用 .catch() 和 Promises

基本用法

使用 Promises 时,您可以使用 .catch() 方法处理错误。如果 Promise 被拒绝,则会调用此方法。

fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error fetching data:', error));

链接多个 Promises

如果您将多个 Promises 链接在一起,您可以在末尾使用一个 .catch() 来处理任何 Promise 中发生的错误。

fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => {
// Process data
return processData(data);
})
.then((result) => {
// Further processing
console.log(result);
})
.catch((error) => console.error('Error in the chain:', error));

延伸阅读

在GitHub上编辑