Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found

Submitted

Using the fetch api

@alidf1372

Desktop design screenshot for the Advice generator app coding challenge

This is a solution for...

  • HTML
  • CSS
  • JS
  • API
2junior
View challenge

Design comparison


SolutionDesign

Solution retrospective


Is the code I wrote optimal?

Community feedback

@johnphillipsdev

Posted

Hey there!

Regarding your question about whether the code is optimal, I'd suggest using an async function with try and catch instead of fetch().then().catch(). Here's why it's more beneficial:

  • Code Readability: The async/await approach enhances code readability and simplifies the flow. It eliminates the need for multiple .then() statements, resulting in cleaner and more concise code.

  • Error Handling: Using try and catch allows you to catch and handle errors within the same block where you perform the asynchronous operation. This leads to cleaner and organized error handling.

  • Error Propagation: Async functions with try and catch offer flexibility in catching and handling errors at different levels, enabling better error propagation and granular error handling.

Here's an example of how the code could be written using an async function:

async function fetchData() {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Request failed');
}
const data = await response.json();
// Process the data here
return data;
} catch (error) {
// Handle any errors here
console.error('An error occurred:', error);
throw error; // Optionally, re-throw the error
}
}

// Call the async function
fetchData()
.then(data => {
// Handle the data here
})
.catch(error => {
// Handle any errors here
});

I hope this explanation clarifies the benefits of using async functions with try and catch for your code.

Marked as helpful

0

Please log in to post a comment

Log in with GitHub
Discord logo

Join our Discord community

Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!

Join our Discord