promise & async await
promise & async await
by oktaviardi pratama
HTML
// handle full filled (resolved) promises
<div>promise.then((res) => {})</div>
<br>
// handle failed (err) promises
<div>promise.then((err) => {})</div>
JavaScript
async function getData(url){
try {
await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
//body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {arguments
if (data.error) {
throw new Error('Network response was not ok');
}
console.log('data : ', data);
})
.catch(error => {
console.error('Error:', error);
throw new Error(error);
}).finally(() => {
});
console.log('will print after promise done')
} catch(e){
console.log('Error:', e)
throw new Error('Network response was not ok');
}
}
getData('https://cors-anywhere.herokuapp.com/https://boredapi.com/api/sactivity').then((data) => console.log(data))
.catch((error) => alert(error));