One thing to remember
fetch starts a network request. await pauses only inside an async function until that promise settles.
Your page should not assume the internet works. Always handle loading, success, and error states.
What fetch returns
fetch(url) does not directly give you the data. It gives you a Response object.
For most APIs, call await response.json() to read the JSON body. Also check response.ok so bad status codes do not look like success.
Small API example
This function gets a random programming joke from a public API. You can use the same shape for weather, college events, UPI expense logs from your own backend, or hackathon project data.
Notice the order: fetch, check, parse JSON, return clean data.
async function getJoke() {
const url = "https://official-joke-api.appspot.com/random_joke";
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const data = await response.json();
return {
setup: data.setup,
punchline: data.punchline
};
}Show it on page
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
const resultBox = document.querySelector("#result");
async function showJoke() {
resultBox.textContent = "Loading...";
try {
const joke = await getJoke();
resultBox.textContent = `${joke.setup} ${joke.punchline}`;
} catch (error) {
resultBox.textContent = "Could not load data. Check your internet and try again.";
console.error(error);
}
}
showJoke();Do not guess timing
A common bug is using data before it has arrived. If a function uses await, mark it async and await it where you need the result.
Do not write code that depends on a network result outside the async flow.
// Wrong: jokePromise is not the final joke data
const jokePromise = getJoke();
console.log(jokePromise.setup);
// Right
const joke = await getJoke();
console.log(joke.setup);Use AI carefully
Ask AI to write the first fetch function, not the whole project. Then check three things yourself: the API URL, response.ok handling, and the exact JSON field names.
If the API returns data.setup but the AI writes data.title, your app will show undefined. Open the API URL in the browser once and inspect the JSON.
Prompt you can use:
Write a JavaScript async function that fetches JSON from this API URL: <paste URL>.
It should check response.ok, parse JSON, return only these fields: <field names>.
Add try/catch in the UI function, not inside the data function.Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done