Quiz

How do you handle errors in asynchronous operations?

Topics
AsyncJavaScript
在GitHub上编辑

TL;DR

To handle errors in asynchronous operations, you can use try...catch blocks with async/await syntax or .catch() method with Promises. For example, with async/await, you can wrap your code in a try...catch block to catch any errors:

async function fetchData() {
try {
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);
}
}

With Promises, you can use the .catch() method:

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

Using try...catch with async/await

Basic usage

When using async/await, you can handle errors by wrapping your asynchronous code in a try...catch block. This allows you to catch any errors that occur during the execution of the await statement.

async function fetchData() {
try {
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);
}
}

Nested asynchronous operations

If you have multiple asynchronous operations, you can nest try...catch blocks to handle errors at different levels.

async function fetchData() {
try {
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);
}
}
async function processData() {
try {
await fetchData();
// Additional processing
} catch (error) {
console.error('Error processing data:', error);
}
}

Using .catch() with Promises

Basic usage

When working with Promises, you can handle errors using the .catch() method. This method is called if the Promise is rejected.

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

Chaining multiple Promises

If you have multiple Promises chained together, you can use a single .catch() at the end to handle any errors that occur in any of the Promises.

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));

Further reading

在GitHub上编辑