Lokang 

JavaScript and MySQL

Error handling with Promises and async/await

In JavaScript, Promises and async/await provide a way to handle asynchronous operations and can be useful for error handling.

Promises are objects that represent a value that may not be available yet, but will be resolved at some point in the future. They have a then() method that allows you to chain callbacks that will be executed when the Promise is resolved or rejected.

Here's an example of how to use a Promise for error handling:

function fetchData() {
 return new Promise((resolve, reject) => {
   // Make an asynchronous API call
   fetch("https://example.com/data")
     .then(response => response.json())
     .then(data => resolve(data))
     .catch(error => reject(error));
 });
}
fetchData()
 .then(data => console.log(data))
 .catch(error => console.log("An error occurred: " + error.message));

In this example, the fetchData() function returns a Promise that makes an asynchronous API call using the fetch() method. If the call is successful, the Promise is resolved with the data returned by the API. If there's an error, the Promise is rejected with an error object.

We can handle the result of the Promise using the then() and catch() methods. If the Promise is resolved, the then() callback is executed and the data is logged to the console. If the Promise is rejected, the catch() callback is executed and an error message is logged to the console.

Async/await is a syntax that provides a more concise way to handle Promises. It allows you to write asynchronous code that looks like synchronous code.

Here's an example of how to use async/await for error handling:

async function fetchData() {
 try {
   const response = await fetch("https://example.com/data");
   const data = await response.json();
   return data;
 } catch (error) {
   throw error;
 }
}
try {
 const data = await fetchData();
 console.log(data);
} catch (error) {
 console.log("An error occurred: " + error.message);
}

In this example, the fetchData() function is marked as async, which allows us to use the await keyword to wait for the Promise to resolve or reject. If the Promise is resolved, the await keyword returns the data, and if it's rejected, it throws an error.

We can handle the result of the function using a try-catch block. If the function returns data, the try block is executed, and the data is logged to the console. If the function throws an error, the catch block is executed, and an error message is logged to the console.

Async/await can be useful for error handling because it allows you to write more readable and structured code. However, it's important to note that async/await is still based on Promises, so you should still be familiar with Promise syntax and error handling.