Async Error Handling
Handle errors in async operations
JavaScript Async Error Handling Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Async/await with try-catch
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error.message);
throw error;
}
}
fetchData().catch(error => {
console.error('Unhandled:', error);
});
// Method 2: Promise error handling
function promiseOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
reject(new Error('Random failure'));
} else {
resolve('Success');
}
}, 1000);
});
}
promiseOperation()
.then(result => console.log('Result:', result))
.catch(error => console.error('Error:', error.message));
// Method 3: Multiple async operations
async function fetchMultiple() {
try {
const [data1, data2, data3] = await Promise.all([
fetch('https://api.example.com/data1').then(r => r.json()),
fetch('https://api.example.com/data2').then(r => r.json()),
fetch('https://api.example.com/data3').then(r => r.json())
]);
return [data1, data2, data3];
} catch (error) {
console.error('One or more requests failed:', error);
throw error;
}
}
// Method 4: Promise.allSettled
async function fetchAllSettled() {
const results = await Promise.allSettled([
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2'),
fetch('https://api.example.com/data3')
]);
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Request ${index + 1} succeeded`);
} else {
console.error(`Request ${index + 1} failed:`, result.reason);
}
});
}
// Method 5: Unhandled promise rejection
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
});
// Method 6: Async error wrapper
function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
// Usage in Express
const asyncRoute = asyncHandler(async (req, res) => {
const data = await fetchData();
res.json(data);
});Fetch error: Failed to fetch Error: Random failure One or more requests failed: Error Request 1 succeeded Request 2 failed: Error Request 3 succeeded
Understanding Async Error Handling
Async error handling requires special care.
Async/Await
Promises
Promise.all
Promise.allSettled
Unhandled Rejections
Best Practices
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.
Practical Learning Notes for Async Error Handling
This JavaScript program is part of the "Error Handling" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.