Lesson 8 of 8 · 12 min · 2 hands-on steps
Getting Data from Servers (async & fetch)
Wait for slow things without freezing your app, using promises and async/await.
Some things take time
Asking a server for data might take 50ms or 5 seconds. If JavaScript just stopped and waited, your whole page would freeze. Instead, slow operations return a promise: "I'll give you the answer later."
console.log("1. Ask for data");
setTimeout(() => console.log("3. Data arrived!"), 500);
console.log("2. Keep doing other things");async / await: write it top to bottom
function fakeServer() {
return new Promise((resolve) => setTimeout(() => resolve({ temp: 21 }), 300));
}
async function showWeather() {
console.log("Loading…");
const data = await fakeServer(); // wait here, without freezing the page
console.log(`It's ${data.temp}°C`);
}
showWeather();fetch: talking to real servers
In the browser, fetch gets data from a URL. Most APIs send JSON:
async function loadUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const user = await response.json();
return user;
}
Always plan for failure
Networks fail: Wi-Fi drops, servers crash. Wrap risky calls in try / catch and show the user something helpful:
try {
const user = await loadUser(42);
render(user);
} catch (err) {
showMessage("Couldn't load your profile. Check your connection and try again.");
}
Good apps handle three states for every request: loading, success, and error. Interviewers notice when you remember all three.
🧪 Practice: 2 steps
0 / 2 doneStep 1 of 2 · Wait for the data
getUser() pretends to ask a server for a user. It returns a promise.
Write async function showUser() that awaits getUser() and returns the string "Ada (ada@example.com)", built from the user's name and email.
function getUser() {
return new Promise((resolve) =>
setTimeout(() => resolve({ name: "Ada", email: "ada@example.com" }), 50),
);
}
async function showUser() {
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Handle errors
getPosts() sometimes fails. Write async function loadPosts() that returns the posts array, or returns the string "Could not load posts" if getPosts() throws. Use try / catch.
async function getPosts(shouldFail) {
await new Promise((r) => setTimeout(r, 20));
if (shouldFail) throw new Error("Network down");
return ["Hello world", "My first post"];
}
async function loadPosts(shouldFail) {
}
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What does await do?
fetch(url) resolved with status 404. Does fetch throw an error?
Create a free account to track your progress.