Category: javascript
fetch() Method in JavaScript
Published on 15 Mar 2026
Explanation
The fetch() method is used to make
HTTP
requests in JavaScript. It returns a
Promise.
Code:
fetch('https://api.example.com/data');
Explanation
Handling JSON response using fetch().
Code:
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data));
Explanation
Handling errors in fetch using
catch().
Code:
fetch('https://api.example.com/data')
.then(res => res.json())
.catch(err => console.error(err));
Explanation
Using async/await with fetch for
cleaner syntax.
Code:
async function getData() {
const res = await
fetch('https://api.example.com/data');
const data = await res.json();
console.log(data);
}
Explanation
Checking HTTP status before processing
response.
Code:
fetch('https://api.example.com/data')
.then(res => {
if(!res.ok) throw new Error('Error');
return res.json();
})
.then(data => console.log(data));