Skip to main content

Async JavaScript

JavaScript is single-threaded, meaning it can only do one thing at a time. Asynchronous programming lets you start long-running operations (network requests, timers, file reads) without blocking the rest of your code.

The Event Loop

The event loop is how JavaScript handles asynchronous code. Understanding it is fundamental.

Ctrl+Enter
HTML
CSS
JS
Preview

Even with a 0ms delay, the timeout callback runs after the synchronous code finishes. The event loop processes the call stack first, then checks the callback queue.

Callbacks

A callback is a function passed to another function to be called later.

Ctrl+Enter
HTML
CSS
JS
Preview

Callback Hell

Nested callbacks quickly become unreadable:

Ctrl+Enter
HTML
CSS
JS
Preview

This is why promises were invented.

Promises

A Promise represents a value that may not be available yet. It has three states: pending, fulfilled, or rejected.

Creating a Promise

Ctrl+Enter
HTML
CSS
JS
Preview

Consuming Promises with .then() and .catch()

Ctrl+Enter
HTML
CSS
JS
Preview

Promise Chaining

Chaining flattens the callback hell pattern:

Ctrl+Enter
HTML
CSS
JS
Preview

Async/Await

async/await is syntactic sugar over promises that makes asynchronous code look synchronous.

Ctrl+Enter
HTML
CSS
JS
Preview

Rewriting the Callback Hell Example

Ctrl+Enter
HTML
CSS
JS
Preview

Clean, readable, and easy to debug.

The Fetch API

fetch is the modern way to make HTTP requests in the browser.

GET Request

Ctrl+Enter
HTML
CSS
JS
Preview

POST Request

Ctrl+Enter
HTML
CSS
JS
Preview

Always Check response.ok

A common mistake is forgetting that fetch does not throw on HTTP errors like 404 or 500. You must check response.ok manually.

Running Promises in Parallel

Promise.all

Wait for all promises to resolve. Rejects if any one fails.

Ctrl+Enter
HTML
CSS
JS
Preview

Promise.allSettled

Wait for all promises to complete, regardless of success or failure.

Ctrl+Enter
HTML
CSS
JS
Preview

Promise.race

Returns the result of whichever promise settles first.

Ctrl+Enter
HTML
CSS
JS
Preview

Error Handling Patterns

Try/Catch with Async/Await

Ctrl+Enter
HTML
CSS
JS
Preview

Practical Exercise

Build a simple API data loader:

Ctrl+Enter
HTML
CSS
JS
Preview

Key Takeaways

  • JavaScript uses the event loop to handle async operations on a single thread.
  • Promises replace nested callbacks with chainable .then() calls.
  • async/await makes promise-based code read like synchronous code.
  • Always check response.ok when using fetch — it does not throw on HTTP errors.
  • Use Promise.all for parallel requests and Promise.allSettled when you need results from all regardless of failures.