Asynchronous JavaScript: Callbacks, Promises and async/await
Handle work that finishes later, from callbacks to promises to async/await, including parallelism, cancellation and error handling.
Intermediate · about 7 hours · difficulty 3/5
Learn first: Events and Event Delegation
Almost everything interesting on the web is asynchronous: network requests, timers, user input, reading files. JavaScript runs on a single thread, so it cannot wait by blocking; it registers work to finish later.
Three generations
- Callbacks: pass a function to run when done (
setTimeout(fn, 1000)). Nesting many leads to "callback hell" and scattered error handling. - Promises: an object representing a future value that is pending, then fulfilled or rejected. Chain with
.then(), handle failures with.catch(), clean up with.finally(). - async/await: syntax over promises. An
asyncfunction always returns a promise;awaitpauses that function (not the whole page) until the promise settles. Usetry/catchfor errors.
Combinators
Promise.allruns in parallel and rejects if any fails.Promise.allSettledwaits for all and reports each result.Promise.raceandPromise.anytake the first to settle or succeed.
Common mistakes
- Awaiting in a loop when requests are independent. Start them together and
await Promise.all(...)instead. - Forgetting
await, so you get a Promise object instead of data. - Not returning a promise from a
.then()callback, breaking the chain. - Ignoring cancellation: use
AbortControllerso a stale search request does not overwrite newer results (a race condition).
Good enough to move on
You can wrap a callback API in a promise, fetch three endpoints in parallel with proper error handling, and cancel an in-flight request when the user types again.
Key concepts
- Callbacks and callback hell
- Promise states and chaining
- async and await
- Error handling in async code
- Promise.all, allSettled, race, any
- Sequential vs parallel awaits
- AbortController and cancellation
- Promisifying callback APIs
Mini project
Build a movie search box that queries a free public API, debounces input, cancels stale requests with AbortController, and shows loading, empty and error states.
Check yourself
What happens if one of three promises passed to Promise.all rejects, and when would you choose allSettled instead?
Free resources
- Promises, async/await (javascript.info)
- Using promises (MDN)