48
loading...
This website collects cookies to deliver better user experience
fetch()
returns a promise, we can use async/await syntax to make our code cleaner and easy to read.GET
, POST
, etc.fetch()
and pass it the required arguments. The fetch method accepts two arguments:headers
, body
, and all other options.
const response = await fetch(URL, {options object});
fetch()
returns a promise, we can use then
and catch
methods of promises to handle the requests. The promise gets resolved if the request is completed. On the other hand, if the request fails due to any error, the promise will be rejected.fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
fetch()
you're only allowed to do GET requests. That's enough if you only want to get data from an API. However, you can still pass the configuration object as a second argument if you want to do other HTTP requests like POST
for example.fetch
and pass it the API URL as a first argument. Since fetch returns a promise, we used then
method to get the response from the API in a JSON format and catch
method to handle an error if it occurs. As a result, the requested data gets printed in the console. You can take that data and display anywhere on your page if you want.then
catch
syntax in our code.async
. The keyword await
is permitted inside the function.const API_URL = 'https://jsonplaceholder.typicode.com/users';
async function fetchUsers() {
const response = await fetch(API_URL)
const users = await response.json();
return users;
}
fetchUsers().then(users => {
users; // fetched users
});
async
to the begining of the function. Then we used the keyword await
when assigning the variables. Since fetchUsers
is an asynchronous function, it returns a promise. As a result, we used one then
method to handle the promise.users
that we got from the API. You can display it on the page if you want.try
and catch
to handle errors if you want. Here is the same example above, but now adding error handling:const API_URL = 'https://jsonplaceholder.typicode.com/users';
async function fetchUsers() {
try{
const response = await fetch(API_URL)
const users = await response.json();
return users;
}catch(err){
console.error(err);
}
}
fetchUsers().then(users => {
users; // fetched users
});