惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - Franky
有赞技术团队
有赞技术团队
博客园 - 司徒正美
量子位
N
News and Events Feed by Topic
T
Threatpost
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
酷 壳 – CoolShell
酷 壳 – CoolShell
C
CERT Recently Published Vulnerability Notes
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
Intezer
人人都是产品经理
人人都是产品经理
T
Tenable Blog
IT之家
IT之家
雷峰网
雷峰网
腾讯CDC
博客园 - 聂微东
V
Visual Studio Blog
S
SegmentFault 最新的问题
Scott Helme
Scott Helme
Spread Privacy
Spread Privacy
月光博客
月光博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
大猫的无限游戏
大猫的无限游戏
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
罗磊的独立博客
N
Netflix TechBlog - Medium
J
Java Code Geeks
宝玉的分享
宝玉的分享
F
Full Disclosure
WordPress大学
WordPress大学
A
Arctic Wolf
小众软件
小众软件
AWS News Blog
AWS News Blog
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
AI
AI
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
N
News | PayPal Newsroom
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Asynchronous JavaScript
Brendon O'Ne · 2026-05-20 · via DEV Community

When we write JavaScript or TypeScript, most of our code runs from top to bottom, line by line. This is what we usually think of as synchronous code. One line runs, then the next, then the next.

But when we need to get information from a server, things are different. We cannot just freeze the whole application while we wait for that data to come back. If a website or app did that, most users would probably leave before anything loaded.

So JavaScript needed a way to let certain tasks happen in the background while the rest of the application kept running. That way, we can show loading states, keep the page interactive, and update the UI once the data finally returns.

This is where asynchronous JavaScript comes in. It gives us a way to start a task now and deal with the result later without blocking the rest of our code. Over time, JavaScript introduced different ways to handle this, starting with callbacks and XMLHttpRequest, then moving to promises, the Fetch API, and finally async/await.

In this post, I am going to walk through that progression and show how asynchronous JavaScript evolved into what we use today.

Callbacks and XMLHttpRequest

Before promises and async/await, the main way to deal with asynchronous code was with callback functions.

If you have not come across them before, a callback is just a function passed into another function as an argument. That function gets called later once the task is complete.

Back then, one of the main tools used to communicate with servers in the browser was XMLHttpRequest, usually shortened to XHR. Despite the name, it was not only used for XML. It could also be used to work with JSON, which is what we use most often today. Before fetch() became the normal choice, XHR was the standard way to make HTTP requests in the browser.

Here is a simple example:

function getData(callback) {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        callback(null, xhr.responseText);
      } else {
        callback("HTTP error: " + xhr.status);
      }
    }
  };

  xhr.open("GET", "/api/data", true);
  xhr.send();
}

function renderContent(data) {
  var container = document.getElementById("content");
  container.innerHTML = "<p>" + data + "</p>";
}

function showError(error) {
  var container = document.getElementById("content");
  container.innerHTML = "<p>" + error + "</p>";
}

getData(function (error, data) {
  if (error) {
    showError(error);
    return;
  }

  renderContent(data);
});

Enter fullscreen mode Exit fullscreen mode

Let’s break down what is happening here.

First, we create a function called getData that accepts a callback. Inside it, we create an XMLHttpRequest object, which handles the request to the server.

Then we use xhr.onreadystatechange, which runs every time the request changes state. We check for xhr.readyState === 4, which means the request has finished. Once it has, we check the HTTP status code. If it is in the 200 range, the request succeeded, so we pass the response into the callback. If it failed, we pass back an error instead.

After that, we call xhr.open() to configure the request and xhr.send() to send it.

At the bottom, we call getData() and pass in another function. That callback decides what to do next. If there is an error, we show it. If not, we render the returned data on the page.

This worked, and for simple requests it was fine. But the problem started when multiple asynchronous tasks depended on each other.

Imagine needing to fetch a user, then fetch their posts, then fetch the comments for one of those posts. Every step depends on the previous one, which means the callbacks start getting nested inside each other. That is what became known as callback hell.

Here is a simple example of that:

function getUser(userId, callback) {
  setTimeout(function () {
    console.log("Fetched user");
    callback(null, { id: userId, name: "Alice" });
  }, 500);
}

function getPosts(userId, callback) {
  setTimeout(function () {
    console.log("Fetched posts");
    callback(null, [
      { id: 1, title: "First Post", userId: userId },
      { id: 2, title: "Second Post", userId: userId },
    ]);
  }, 500);
}

function getComments(postId, callback) {
  setTimeout(function () {
    console.log("Fetched comments");
    callback(null, [
      { id: 1, text: "Nice post", postId: postId },
      { id: 2, text: "Thanks for sharing", postId: postId },
    ]);
  }, 500);
}

getUser(42, function (err, user) {
  if (err) {
    console.error("Error fetching user:", err);
  } else {
    getPosts(user.id, function (err, posts) {
      if (err) {
        console.error("Error fetching posts:", err);
      } else {
        getComments(posts[0].id, function (err, comments) {
          if (err) {
            console.error("Error fetching comments:", err);
          } else {
            console.log("User:", user);
            console.log("Posts:", posts);
            console.log("Comments for first post:", comments);
          }
        });
      }
    });
  }
});

Enter fullscreen mode Exit fullscreen mode

Even in this small example, the code is already getting deeper, more repetitive, and harder to scan. As the number of requests grows, debugging and maintaining it becomes more of a hassle.

Developers needed a cleaner way to deal with async code.

That is where promises came in.

Promises

Promises gave JavaScript a much cleaner way to handle asynchronous work.

A promise is an object that represents a value we do not have yet, but expect to receive later. That future result can either succeed or fail.

A simple way to think about it is lending a pen to someone. They promise they will give it back. You do not know exactly when that will happen, and there is always a chance they come back without it. But instead of standing there waiting, you go and do other things. Then, once the result comes back, you deal with it.

That is basically how promises work in JavaScript.

A promise can end in two main ways:

  • resolved, meaning the operation succeeded
  • rejected, meaning something went wrong

We usually handle those outcomes with .then() and .catch():

  • .then() handles the resolved value
  • .catch() handles errors or rejections Here is an example of wrapping XHR in a promise:
function apiGet(url) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          var data = JSON.parse(xhr.responseText);
          resolve(data);
        } else {
          reject(new Error("Request failed with status " + xhr.status));
        }
      }
    };

    xhr.open("GET", url, true);
    xhr.send();
  });
}

apiGet("/api/user/42")
  .then(function (user) {
    console.log("User loaded:", user);
  })
  .catch(function (err) {
    console.error("Error:", err);
  });

Enter fullscreen mode Exit fullscreen mode

Here, instead of accepting a callback, apiGet() returns a promise. Inside that promise, we call resolve() when the request succeeds and reject() when it fails.

This means the code that calls apiGet() can decide how to handle the result. That is a big improvement because it separates the request logic from the result-handling logic.

It also gave us a cleaner way to chain async steps together.

function getUser(userId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ id: userId, name: "Alice" });
    }, 500);
  });
}

function getPosts(userId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        { id: 1, title: "First Post", userId: userId },
        { id: 2, title: "Second Post", userId: userId },
      ]);
    }, 500);
  });
}

function getComments(postId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        { id: 1, text: "Nice post", postId: postId },
        { id: 2, text: "Thanks for sharing", postId: postId },
      ]);
    }, 500);
  });
}

getUser(42)
  .then((user) => {
    console.log("User:", user);
    return getPosts(user.id);
  })
  .then((posts) => {
    console.log("Posts:", posts);
    return getComments(posts[0].id);
  })
  .then((comments) => {
    console.log("Comments:", comments);
  })
  .catch((error) => {
    console.error("Something went wrong:", error);
  });

Enter fullscreen mode Exit fullscreen mode

This is still asynchronous, but it is much flatter than the callback version. It reads in a more natural order and is easier to debug.

The Fetch API

As promises became more common, browsers introduced a newer and cleaner way to make HTTP requests called the Fetch API.

The Fetch API is built around promises, which means it works naturally with .then() and .catch(). It quickly became the more modern replacement for XHR and is now what most frontend developers use by default in the browser.

Here is a simple example:

fetch("https://api.example.com/data")
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

Enter fullscreen mode Exit fullscreen mode

Let’s break it down.

First, fetch() sends the request and returns a promise.

When that promise resolves, we get back a response object. That is not the final JSON yet, it is the full HTTP response, so the first thing we often do is check response.ok.

If the request failed, we throw an error so that .catch() can handle it.

If the request succeeded, we call response.json(). That also returns a promise, which is why we need another .then() after it. Once that promise resolves, we finally have access to the parsed data.

Compared to XHR, this is much shorter and easier to follow. We no longer need to manage readyState, create request objects manually, or put all our logic inside event handlers.

But even with fetch and promises, long chains of .then() could still become difficult to read in more complex applications.

That is where async/await made things even cleaner.

Async Await

async/await gave us a way to write asynchronous code that looks much closer to normal synchronous code.

It is important to note that async/await is still built on promises. It does not replace them underneath, it just gives us a nicer syntax to work with them.

There are two main parts:

  • async marks a function as asynchronous
  • await pauses that function until a promise settles

Here is a basic example using fetch():

async function getData() {
  try {
    const response = await fetch("https://api.example.com/data");

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getData();

Enter fullscreen mode Exit fullscreen mode

Here’s what is happening.

First, we add the async keyword to the function. That tells JavaScript we want to use await inside it.

Then we use await with fetch(). Instead of chaining .then(), we store the resolved response in a variable.

After that, we check whether the request succeeded.

Then we use await again with response.json() because parsing the response body is also asynchronous.

Finally, we wrap everything in a try...catch block, which lets us handle errors in one place.

This is one of the reasons async/await became so popular. It is still asynchronous, but it reads more like normal top-to-bottom code.

Here is the earlier user-posts-comments example rewritten using async/await:

function getUser(userId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ id: userId, name: "Alice" });
    }, 500);
  });
}

function getPosts(userId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        { id: 1, title: "First Post", userId: userId },
        { id: 2, title: "Second Post", userId: userId },
      ]);
    }, 500);
  });
}

function getComments(postId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        { id: 1, text: "Nice post", postId: postId },
        { id: 2, text: "Thanks for sharing", postId: postId },
      ]);
    }, 500);
  });
}

async function loadUserData() {
  try {
    const user = await getUser(42);
    console.log("User:", user);

    const posts = await getPosts(user.id);
    console.log("Posts:", posts);

    const comments = await getComments(posts[0].id);
    console.log("Comments for first post:", comments);
  } catch (error) {
    console.error("Error loading data:", error);
  }
}

loadUserData();

Enter fullscreen mode Exit fullscreen mode

This version is much easier to read because the steps happen in a clear order:

  • get the user
  • get the posts
  • get the comments

No deep nesting, no long promise chain, and much less repeated error handling.

One important thing to remember is that await only pauses the async function it is inside. It does not block the whole browser or freeze the rest of your application.

That is the key difference. It looks synchronous, but it still behaves asynchronously under the hood.

Conclusion

Asynchronous JavaScript has come a long way.

We started with callbacks and XMLHttpRequest, which worked but quickly became messy when multiple requests depended on each other. Then promises gave us a cleaner and more structured way to manage async code. After that, the Fetch API made browser requests easier to write, and finally, async/await made asynchronous code feel far more natural to read.

At the end of the day, all of these approaches are solving the same problem: letting JavaScript keep running while waiting for something else to finish.

If you are learning JavaScript today, async/await is probably what you will use most often. But understanding callbacks, promises, and fetch is still really useful, because it helps you understand what is happening underneath and why modern async code looks the way it does.

If you want to learn more about JavaScript, check out: