xxxxxxxxxx
async function getUserAsync(name) {
try{
let response = await fetch(`https://api.github.com/users/${name}`);
return await response.json();
}catch(err){
console.error(err);
// Handle errors here
}
}
Async await arrow function with try catch block
xxxxxxxxxx
const getUserAsync = async (name) => {
try{
const response = await fetch(`https://api.github.com/users/${name}`);
const data = await response.json();
// do something with the data (eg. setUser in React)
return data
}catch(error){
throw (error);
}
}
xxxxxxxxxx
Code for fetch Async/await-
// declare the async data fetching function
const fetchData = async() => {
try{
// get the data from the api
const get_data = await fetch('URL');
// convert the data to json
const json = await get_data.json();
}
catch(error){
// make sure to catch any error
console.log(error)
}
}
// call the function
fetchData()