We use error handling with async and await to catch problems when waiting for tasks that take time, like loading data from the internet. It helps keep the program running smoothly without crashing.
Error handling with async and await in Javascript
async function example() { try { const result = await someAsyncTask(); // use result here } catch (error) { // handle error here } }
The async keyword makes a function return a promise and allows using await inside it.
The try...catch block is used to catch errors that happen during the awaited task.
async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } }
async function waitAndFail() { try { await Promise.reject(new Error('Oops!')); } catch (error) { console.log('Caught error:', error.message); } }
This program waits for a promise that gives the number 42 and prints it. If there was an error, it would print the error instead.
async function getNumber() { try { const number = await Promise.resolve(42); console.log('Number is', number); } catch (error) { console.log('Error:', error); } } getNumber();
Always use try...catch inside async functions to handle errors gracefully.
Without try...catch, errors in awaited promises can crash your program or go unnoticed.
You can also use .catch() on promises, but try...catch with async/await looks cleaner and is easier to read.
Use async and await to write asynchronous code that looks like normal code.
Wrap awaited calls in try...catch to catch and handle errors.
This helps keep your program running smoothly and makes debugging easier.