All 28 lessons ▾
Inside JavaScript · Lesson 24 of 28
async/await Part 2: Real Fetch Calls, Errors and async vs .then
So last time, we saw what await pauses. Now today, real code: fetching from a server, handling errors properly, and two traps that slow down real apps.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- await fetch, then await response.json()
- Errors: try, catch and finally
- fetch doesn't reject on a 404: check response.ok
- Independent awaits? Use Promise.all
- No await inside forEach: use for...of
- async/await is sugar over promises
Part 1A real fetch with await
So in part one, we learned what async and await do, and what await really pauses. So now let's use them for real. Fetching data from a server, handling errors properly, and a few traps that catch even experienced developers. So let's start with a real API call.
1async function getUser() {2 const response = await fetch("https://api.github.com/users/octocat");3 const user = await response.json();4 console.log(user.name);5}6 7getUser();8// The OctocatSo here's a real call to GitHub's public API. Remember, fetch is given to us by the browser, not by JavaScript itself. It returns a promise, so we await it, and get the response. But now the response body is a stream, not ready-made data. So we call response.json, which returns another promise. We await that too, and finally, we have the user object. user.name is, The Octocat. Two awaits, two promises, and the code reads like a simple story, top to bottom. Now how long was getUser suspended at that first await? Open the Network tab, and you'll see it. A few hundred milliseconds, the time the request took.
1function getUser() {2 fetch("https://api.github.com/users/octocat")3 .then((response) => response.json())4 .then((user) => console.log(user.name));5}And now here's the same thing with then. It works exactly the same. fetch, then json, then the name. For a short chain like this, both look fine. But as the steps grow, and you need values from earlier steps, the await version stays flat and readable, while the then version starts to nest again.
Part 2Handling errors
Now, real servers fail. Networks drop. Users type wrong names. So how do we handle errors with await? Let's see.
1async function getUser(name) {2 try {3 const response = await fetch("https://api.github.com/users/" + name);4 const user = await response.json();5 console.log(user.name);6 } catch (err) {7 console.log("Oops:", err.message);8 }9}So with await, we use the good old try and catch. So put the awaits inside try. If any awaited promise rejects, say the network is down, or the address is wrong, JavaScript jumps straight into catch, with the error. You'd see, type error, failed to fetch. And in catch, you decide what the user sees. A friendly message, a retry button, or an error page. So just like a then chain jumps to its catch. And the error is a normal error object, with a message. So async and await let you handle async errors exactly like normal ones.
1async function getUser(name) {2 try {3 const response = await fetch("https://api.github.com/users/" + name);4 if (!response.ok) {5 throw new Error("User not found: " + response.status);6 }7 const user = await response.json();8 console.log(user.name);9 } catch (err) {10 console.log("Oops:", err.message);11 }12}13 14getUser("no-such-user-xyz");15// Oops: User not found: 404But now here's a trap that catches a lot of people. fetch only rejects when the network itself fails. If the server answers with an error, like four oh four, not found, fetch still resolves! The promise is fulfilled, with a response that says four oh four. So you must check response.ok yourself. If it's false, throw your own error. Now a wrong username prints, oops, user not found, four oh four. Remember this one. It's a very common bug.
1async function loadProfile(name) {2 showSpinner();3 try {4 const user = await getUser(name);5 render(user);6 } catch (err) {7 showError(err.message);8 } finally {9 hideSpinner();10 }11}And just like promises have finally, try and catch have finally too. So show the spinner, try to load the user, catch any error, and finally, always hide the spinner. So whether it worked or failed, the spinner goes away. So this is a pattern you'll write again and again in real apps.
1async function getUser(name) {2 const response = await fetch("https://api.github.com/users/" + name);3 return response.json();4}5 6getUser("octocat")7 .then((user) => console.log(user.name))8 .catch((err) => console.log("Oops:", err.message));Now there's also a second way. Remember, an async function returns a promise. If something inside it throws, or an awaited promise rejects, that returned promise is rejected. So you can skip try and catch inside, and attach a catch when you call it. Both ways work. So use try and catch when the function itself knows how to handle the error, and an outside catch when the caller should decide.
1// in a module, <script type="module">2const user = await getUser("octocat");3 4// in a normal script: an async IIFE5(async function () {6 const user = await getUser("octocat");7 console.log(user.name);8})();And now how do you use await outside a function, at the very top of your file? In a JavaScript module, you can simply write await at the top level. Modern browsers and Node support that. In a normal script, wrap your code in an async function, and call it straight away. That's called an async IIFE, an immediately invoked function expression. The brackets around the function create it, and the brackets at the end call it. So you'll see this pattern in a lot of older code and tutorials.
So remember this. With async and await, errors are handled with try and catch, and cleanup goes in finally. And with fetch, always check response.ok, because a four oh four, or a five hundred, doesn't reject the promise. So you have to turn it into an error yourself.
Part 3Two traps to avoid
Now, two traps that slow down, or even break, a lot of real code. Even in big companies.
1async function loadPage() {2 const user = await getUser(); // 2 seconds3 const movies = await getMovies(); // 2 seconds4 // total: 4 seconds5}6 7async function loadPageFast() {8 const [user, movies] = await Promise.all([getUser(), getMovies()]);9 // total: 2 seconds10}So trap one. Awaiting things one by one, when they don't depend on each other. Here, getUser takes two seconds, and getMovies takes two seconds. Now with two awaits in a row, getMovies doesn't even start until getUser is done. Four seconds total. But the movies don't need the user. So start both together, with Promise.all, and await them once. Now they run side by side, and the page loads in two seconds. We'll go deep into Promise.all in the next episode.
1async function saveAll(ids) {2 ids.forEach(async (id) => {3 await saveSeat(id);4 });5 console.log("All seats saved?"); // runs first!6 7 for (const id of ids) {8 await saveSeat(id);9 }10 console.log("All seats saved!"); // really done11}Now trap two. Using await inside forEach. It looks right, but forEach doesn't wait for async functions. It starts all of them, and moves on immediately. So, all seats saved, prints before any seat is actually saved! Now the fix is a simple for of loop. Inside it, await really pauses the loop, one seat at a time, and the next line runs only when everything is done. Or, if the seats can be saved together, use Promise.all again.
Part 4async/await or then?
So finally, the big question. Should you use async and await, or then and catch?
1async function bookMovie(seats) {2 const id = await bookSeats(seats);3 const payment = await makePayment(id);4 const ticket = await sendTicket(payment);5 await addRewards(ticket);6 console.log("All done!");7}So remember our movie booking chain from the last episodes? Here it is with await. Book, pay, send, reward. Each line waits for the one before, and every variable is right there, easy to use later. Now compare that with the then chain. Same steps, same promises underneath, but this one reads like plain, synchronous code. And if any step fails, one try and catch around all four lines handles it, just like a single catch at the end of a chain.
So here's the truth. async and await are syntactic sugar over promises. Underneath, it's exactly the same promises, the same microtasks, the same event loop. Nothing new happens behind the scenes. So it's just a nicer way to write it. So which should you use? In most modern code, async and await, because it's easier to read and debug. But you'll still use then for quick one-liners, and Promise.all for parallel work. And you must understand both, because interviewers will ask about both.
1async function a() {2 throw new Error("Boom");3}4 5a()6 .then(() => console.log("then"))7 .catch((err) => console.log("catch:", err.message));8console.log("end");What prints, and in what order?
Show the answer
So calling a doesn't throw at the call site. Since a is async, the error turns into a rejected promise. JavaScript moves on, and prints end first. Now the rejection reaches catch, which prints, catch, Boom. And then never runs. So end, then catch Boom. So remember, an error inside an async function never escapes as a normal throw. Did you get both parts? Great job!
Which trap had you fallen into before?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.