In this tutorial, our goal is to understand how to handle errors effectively in asynchronous JavaScript code. We will be focusing on the use of try/catch blocks within promises and async/await syntax.
By the end of this tutorial, you will learn:
Prerequisites: Basic understanding of JavaScript and asynchronous programming.
JavaScript is single-threaded, which means it can only do one thing at a time. To overcome this limitation and avoid blocking the main thread, JavaScript uses asynchronous programming.
A Promise is an object representing the eventual completion or failure of an asynchronous operation. To handle errors in promises, we can use .catch()
method. However, using try/catch blocks can provide better error handling.
Consider this promise:
let promise = new Promise((resolve, reject) => {
throw new Error('Promise failed!');
});
To handle the error, we can use try/catch as follows:
try {
promise.catch(error => console.error(error));
} catch (error) {
console.error('Caught:', error);
}
Async/await syntax is a new and cleaner way to handle asynchronous operations. It makes asynchronous code look and behave like synchronous code.
Here's how you can use try/catch with async/await:
async function asyncFunction() {
try {
let response = await fetch('https://api.github.com/users/github');
let user = await response.json();
console.log(user.name);
} catch (error) {
console.error('Caught:', error);
}
}
let promise = new Promise((resolve, reject) => {
throw new Error('Promise failed!');
});
try {
promise.catch(error => console.error(error)); // This will log: Error: Promise failed!
} catch (error) {
console.error('Caught:', error);
}
In this example, we create a promise that immediately throws an error. We then use a try/catch block to catch any errors thrown by the promise.
async function asyncFunction() {
try {
let response = await fetch('https://api.github.com/users/github');
let user = await response.json();
console.log(user.name); // This will log: GitHub
} catch (error) {
console.error('Caught:', error);
}
}
asyncFunction();
In this example, we define an async function that makes a fetch request to the GitHub API. It then tries to parse the response as JSON and log the user's name. If any of these operations fail, the catch block will log the error.
We've covered:
To continue learning, you might want to explore:
Solution:
async function fetchData(url) {
try {
let response = await fetch(url);
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Caught:', error);
}
}
fetchData('https://api.github.com/users/github');
Solution:
function delay() {
return new Promise(resolve => setTimeout(resolve, 2000));
}
try {
delay().then(() => console.log('Resolved after 2 seconds'));
} catch (error) {
console.error('Caught:', error);
}
Remember to always handle errors in your asynchronous code to ensure your application runs smoothly.