Async/Await Error Handling
Try/catch with async functions
async function fetchData(shouldFail) {
await new Promise(r => setTimeout(r, 100));
if (shouldFail) throw new Error("Network error");
return { data: [1, 2, 3] };
}
(async () => {
// Success
try {
const result = await fetchData(false);
console.log("Success:", result);
} catch (err) {
console.error("Failed:", err.message);
} finally {
console.log("cleanup 1");
}
// Failure
try {
const result = await fetchData(true);
console.log("Success:", result);
} catch (err) {
console.error("Failed:", err.message);
} finally {
console.log("cleanup 2");
}
})();