Promises and Fetch API
Promises and Fetch API:
Handling asynchronous operations in JavaScript is crucial, especially when dealing with tasks like making network requests.
Promises and the fetch API provide a clean and efficient way to manage asynchronous code.
Promises:
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It provides a way to handle asynchronous code more elegantly.
// Example: Simulating an asynchronous operation
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve('Data fetched successfully');
} else {
reject(new Error('Failed to fetch data'));
}
}, 1000);
});
};
// Using the Promise
fetchData()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error('Error:', error.message);
});
In this example, fetchData returns a Promise. The then method is used to handle the resolved value, and the catch method is used to handle errors.
Fetch API:
The Fetch API provides a modern, promise-based way to make network requests. It is widely used for making HTTP requests and handling responses.
// Example: Making a GET request with fetch
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error.message);
});
In this example, fetch returns a Promise that resolves to the Response to that request, whether it is successful or not. The json method is used to extract JSON data from the response.
Async/Await:
Async/await is a syntax for handling asynchronous code that makes it look and behave like synchronous code. It's built on top of promises.
// Using async/await with fetch
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log('Data:', data);
} catch (error) {
console.error('Error:', error.message);
}
}
fetchData();
In this example, fetchData is an asynchronous function that uses await to wait for the promises returned by fetch and response.json() to resolve.