js fetch async code example
Example 1: async function fetchJson
async function getUserAsync(name)
{
let response = await fetch(`https://api.github.com/users/${name}`);
let data = await response.json()
return data;
}
getUserAsync('yourUsernameHere')
.then(data => console.log(data));
Example 2: async fetch api call
async function getUserAsync(name) {
try{
let response = await fetch(`https://api.github.com/users/${name}`);
return await response.json();
}catch(err){
console.error(err);
}
}
Example 3: javascript async fetch file html
async function () {
element.innerHTML = await (await fetch('./filetofetch.html')).text();
}
Example 4: how to make an async function
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();
Example 5: async
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();