Lesson 6 of 6 · 5 min
Async JavaScript and fetch
Why some code has to wait, promises, async and await, loading JSON from an API with fetch, handling errors and loading states, and running requests in parallel.
On this page
Some work takes time: loading data from a server, reading a file, waiting for a timer. JavaScript doesn't stop and wait for it. It starts the work, carries on, and handles the result when it arrives. That is asynchronous code.
Promises
A promise is an object that stands for a value you'll get later. It is either pending, fulfilled with a value, or rejected with an error.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
wait(1000).then(() => console.log("One second later"))
async and await
await pauses an async function until a promise settles, so asynchronous code reads like normal top-to-bottom code:
async function run() {
console.log("Start")
await wait(1000)
console.log("One second later")
}
run()
Only the async function pauses. The rest of the page keeps working.
Loading data with fetch
fetch requests a URL and returns a promise for the response:
async function loadPosts() {
const res = await fetch("https://blog.khanwaseem.com/wp-json/wp/v2/posts?per_page=5")
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
const posts = await res.json()
return posts
}
Two steps, two awaits: one for the response headers, one to read and parse the body. fetch only rejects when the network fails. A 404 or 500 still "succeeds", so always check res.ok.
Handling errors
Wrap awaited code in try...catch:
async function showPosts() {
const list = document.querySelector("#posts")
list.textContent = "Loading…"
try {
const posts = await loadPosts()
list.replaceChildren(
...posts.map((post) => {
const li = document.createElement("li")
const a = document.createElement("a")
a.href = post.link
a.textContent = post.title.rendered
li.append(a)
return li
})
)
} catch (error) {
console.error(error)
list.textContent = "Couldn't load posts. Please try again."
}
}
showPosts()
Every request needs three states: loading, success and error. Showing all three is the difference between a page that feels broken and one that feels solid.
Sending data
const res = await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "asha@example.com" }),
})
Running requests in parallel
Awaiting one request after another is slow when they don't depend on each other. Start them together and wait for all of them:
const [courses, posts] = await Promise.all([
fetch("/api/courses").then((r) => r.json()),
fetch("/api/posts").then((r) => r.json()),
])
Promise.all rejects as soon as any request fails. Promise.allSettled waits for all of them and tells you which succeeded.
Cancelling and timeouts
const res = await fetch(url, { signal: AbortSignal.timeout(5000) })
If the server takes more than five seconds, the request is cancelled and fetch rejects, so your error state shows instead of an endless spinner.
The event loop, in one paragraph
JavaScript runs one piece of code at a time. When asynchronous work finishes, its callback waits in a queue until the code currently running is done. That's why a long loop freezes the page: nothing else, not even a click, can run until it finishes. Keep work in event handlers short, and let await give the browser room to breathe.
Try it
Use fetch to load https://jsonplaceholder.typicode.com/users and render each user's name in a list, with a loading message and an error message. Then break the URL on purpose and check that your error state appears.
That completes the JavaScript Crash Course. To store data on a server, continue with Databases and SQL.
More from JavaScript Crash Course
- Lesson 1 · 5 minValues and variablesNumbers, strings, booleans, null and undefined, let and const, template literals, and why you should always compare with ===.
- Lesson 2 · 5 minFunctionsDeclare and call functions, parameters with defaults, return values, arrow functions, scope and closures, and passing functions as values.
- Lesson 3 · 5 minArrays and objectsStore lists and records, loop over them, transform them with map, filter, find and reduce, and copy them safely with spread and destructuring.