Getting JSON from HTTP request
JavaScript functions are often asynchronous -- the script continues to run before a step has completed!
You can use async with await or you can chain steps in sequence with fetch.then().then()
Javascript "fetch"
async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}fetch().then().then()
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error:', error);
});