| async/await in JavaScript | Error Handling in Javascript (try catch) | |
Fetch API in JavaScript |
The Fetch API is a modern interface for making HTTP requests in JavaScript. It provides a more powerful and flexible way to interact with resources over the network compared to older methods like XMLHttpRequest. It offers a powerful, flexible, and promise-based way to fetch resources from a server, making asynchronous operations more straightforward and cleaner.
Definition: The fetch() API is a modern JavaScript interface used to make HTTP requests to servers. It returns a Promise that resolves to the response of the request.
The fetch() method is a global function that takes one mandatory argument: the URL of the resource you want to retrieve. It returns a Promise that resolves to a Response object as soon as the server responds with headers.
The process typically involves two stages:
fetch() with the URL. This returns a promise that resolves with a Response object. The promise only rejects on network failures, such as a lack of internet connection or a bad URL.response.json(), to parse the data. This returns a second promise that resolves with the final data.Using async/await is the most modern and readable way to use the Fetch API.
async function fetchPosts() {
try {
// Stage 1: Send the request and await the Response object
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
// Manually check if the HTTP status is ok (200-299)
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Stage 2: Parse the response body and await the JSON data
const data = await response.json();
console.log(data);
} catch (error) {
// Catch network errors and our custom HTTP status error
console.error('Fetch error:', error);
}
}
fetchPosts();
fetch(url, options)
.then(response => response.json())
.then(data => {
// handle the data
})
.catch(error => {
// handle the error
});
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => {
console.log("Post title:", data.title);
})
.catch(error => {
console.error("Fetch error:", error);
});
By default, fetch() uses the GET method. You can specify a different HTTP method by passing an optional second argument—a configuration object.
async function createPost() {
const newPost = {
title: 'foo',
body: 'bar',
userId: 1,
};
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(newPost), // Convert the JavaScript object to a JSON string
};
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', options);
const result = await response.json();
console.log('Post created:', result);
} catch (error) {
console.error('Error:', error);
}
}
createPost();
async/awaitresponse.json(), response.text(), and response.blob() simplify the process of handling various response types.fetch() promise only rejects on network errors. For HTTP error status codes like 404 or 500, the promise still resolves, and you must manually check the response.ok property.response.ok before parsingasync/await for cleaner syntaxtry...catch or .catch()AbortController to cancel requests if needed.catch() alone. Manually check response.ok or the status code to handle HTTP errors explicitly.try...catch for error handling..then(), return the result of the next operation to avoid nesting.Promise.all() to fire them all at once rather than waiting for each one to complete sequentially.AbortController interface.response.json() consume the response body stream. If you need to read it multiple times, use response.clone() first. | async/await in JavaScript | Error Handling in Javascript (try catch) | |