Asynchronous JavaScript and fetch

Master promises, async/await and the event loop, and call APIs with fetch while handling loading and errors properly.

Beginner · about 8 hours · difficulty 3/5

Learn first: JavaScript Fundamentals

Almost everything a full-stack app does is asynchronous: fetching data, querying the database, sending emails, verifying a payment.

The event loop

JavaScript runs on a single thread. Slow work (network, disk, timers) is handed off, and its callback is queued for later. This is why Node.js can handle many requests at once without threads, and why a long synchronous loop freezes the whole page or server.

Promises and async/await

  • A promise represents a value that will arrive later, or an error.
  • async/await lets you write asynchronous code that reads top to bottom.
  • Use try/catch around awaited calls, and always handle rejections.
  • Run independent work in parallel with Promise.all, and use Promise.allSettled when partial failure is acceptable.

fetch

fetch(url, options) returns a promise of a Response. Remember that fetch only rejects on network failure; a 404 or 500 still resolves, so check response.ok. Send JSON with a Content-Type header and JSON.stringify.

Pitfalls

  • Awaiting inside a loop when the calls could run in parallel.
  • Forgetting to show loading and error states in the UI.
  • Unhandled promise rejections that crash a Node.js process.

You are ready to move on when you can fetch data from two APIs in parallel, handle a failed response gracefully, and explain why the order of console logs in an async example is what it is.

Key concepts

  • Event loop and call stack
  • Promises
  • async/await
  • Error handling in async code
  • Promise.all and allSettled
  • fetch API and response.ok
  • AbortController and timeouts

Mini project

Build a page that fetches GitHub profiles for a list of usernames in parallel, shows a loading state, displays partial results if some fail, and lets the user cancel with AbortController.

Check yourself

Your fetch call to an endpoint returning 500 does not reach the catch block. Why, and how do you fix it?

Free resources