async/await and fetch: Calling an API
async and await let you write promise code that reads top to bottom, like normal code. await pauses the function until the promise is done.
async/await is the modern way to write asynchronous code. It does the same thing as .then() chains, but reads like normal step-by-step code, and errors are handled with ordinary try/catch. Most new JavaScript code uses this style.
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function placeOrder() {
console.log("Placing order...");
await wait(500);
console.log("Order confirmed");
return 101;
}
placeOrder().then(id => console.log("Order id:", id));
// Output:
// Placing order...
// Order confirmed
// Order id: 101fetch: get data from the internet
fetch(url) asks a server for data and returns a promise. Most APIs answer in JSON, so call response.json().
This is how websites get live data: product lists, weather, cricket scores, search results. The browser sends a request to an API (a web address that returns data instead of a web page), waits for the answer, and your code turns the JSON into something on the page. Many APIs need a key and have rules - read their documentation.
<!DOCTYPE html>
<html>
<body>
<pre id="out"></pre>
<script>
function show(...values) {
document.getElementById("out").textContent += values.join(" ") + "\n";
}
async function loadUser() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
if (!res.ok) throw new Error("Server said " + res.status);
const user = await res.json();
show("Name:", user.name);
show("City:", user.address.city);
show("Email:", user.email);
} catch (err) {
show("Could not load the user:", err.message);
}
}
loadUser();
</script>
</body>
</html>▶ Try it yourselfjsonplaceholder.typicode.com is a free practice API with made-up data.
Sending data with POST
async function sendReview(text) {
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Review", body: text }),
});
const saved = await res.json();
console.log("Saved with id", saved.id);
}Show a loading message
- Before
fetch: show "Loading..." and disable the button. - After success: show the data.
- In
catch: show a friendly error and let the user try again. - In
finally: hide "Loading..." and enable the button.
fetch only rejects when the network fails. A 404 or 500 answer still resolves - always check res.ok.- async functions can await promises.
- fetch(url) gets data; response.json() reads it.
- Check res.ok - fetch doesn't reject on 404 or 500.
- Show loading and error states to users.
