Key Differences : Fetch vs Async/Await
Fetch :
1. simple tasks use this fetch.2. Uses with .then and .catch
3. fetch is a modern JavaScript API used to make HTTP requests. It returns a Promise that resolves to the Response object representing the response to the request.
4. Fetch it returns a Promise.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
Async/Await :
1. complex tasks involving multiple asynchronous calls.2. priority wise readability and maintainability.
3. Uses with .await
4. async/await is syntactic sugar built on top of Promises that allows you to write asynchronous code in a synchronous style.
5. Async/await it returns a Promise. Accessed via .json(), .text(), etc., which return Promises.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
fetchData();
No comments:
Post a Comment