Hey everyone, I'm trying to get a solid grasp on asynchronous JavaScript, specifically promises and async/await. I understand the basic concept of non-blocking operations, but I'm struggling with error handling and chaining multiple asynchronous operations in a readable way.
Here's a simplified example I'm working with:
function fetchData(url) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === '/api/data') {
resolve({ data: 'Sample data received!' });
} else {
reject(new Error('Invalid URL'));
}
}, 1000);
});
}
async function processData() {
try {
const response = await fetchData('/api/data');
console.log(response.data);
const moreData = await fetchData('/api/more'); // This will reject
console.log(moreData.data);
} catch (error) {
console.error('An error occurred:', error.message);
}
}
processData();
I get the expected output for the first `fetchData`, but the error message for the second call seems a bit generic. Are there best practices for structuring these `try...catch` blocks when dealing with many sequential async operations?