Junior
How can you handle a promise rejection in an asynchronous function?
sobes.tech AI
Answer from AI
You can use try...catch.
async function processData() {
try {
const result = await fetchData(); // fetchData() may return a promise that is rejected
console.log('Data successfully received:', result);
} catch (error) {
console.error('Error fetching data:', error);
// Additional error handling actions can be performed here
// For example, showing a message to the user or logging
}
}
// Alternative method with .catch() (less common in async/await)
async function processDataAlt() {
await fetchData()
.then(result => {
console.log('Data successfully received:', result);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
Using try...catch is more preferred and idiomatic for async/await. It allows centralizing error handling in one block and appears more synchronous.