@0xabdulkhalid
Posted
Hello there 👋. Congratulations on successfully completing the challenge! 🎉
- I have a suggestion regarding your code that I believe will be of great interest to you.
LET'S REFACTOR YOUR SCRIPT 🟡:
- Currently you have utilized promises to fetch api right ? Instead you can try using
async
/await
which helps you to write a more cleaner and well structured code.
- Here's the refactored code,
let buttonUpdate = document.querySelector('.advice-update');
let adviceId = document.getElementsByClassName('advice-id')[0];
let advicePhrase = document.getElementsByClassName('advice-phrase')[0];
const apiUrl = 'https://api.adviceslip.com/advice';
// Helper function to handle API fetch
async function fetchAdvice() {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`Error getting data from API: ${response.status}`);
}
const data = await response.json();
return data['slip'];
} catch (error) {
console.error(`Error in API request: ${error}`);
}
}
// Event listener for button click
buttonUpdate.addEventListener('click', async function() {
const advice = await fetchAdvice();
if (advice) {
// Update the advice phrase and ID
advicePhrase.innerHTML = advice.advice;
adviceId.innerHTML = `ADVICE #${advice.id}`;
}
});
- The updated code is more readable and easier to follow compared to the callback-based approach.
- Errors can be handled using try/catch blocks, making it easier to manage exceptions. The asynchronous operations are more sequential and straightforward, avoiding the "callback hell" issue, and finally now your code is more maintainable and easier to reason to read.
.
I hope you find this helpful 😄 Above all, the solution you submitted is great !
Happy coding!
Marked as helpful
@yuriown
Posted
@0xabdulkhalid Thank you very much for the suggestion, I'm going to study this subject, it's all very new to me!
@0xabdulkhalid
Posted
You're welcome @yuriown !
Additionally, i would recommend Asynchronous JavaScript learning module from MDN. It's a great resource. You can familiar with some lessons but it's good to refresh the concepts you learned once again!