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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
罗磊的独立博客
T
The Blog of Author Tim Ferriss
The GitHub Blog
The GitHub Blog
Apple Machine Learning Research
Apple Machine Learning Research
The Register - Security
The Register - Security
J
Java Code Geeks
V2EX - 技术
V2EX - 技术
Vercel News
Vercel News
N
News and Events Feed by Topic
腾讯CDC
P
Proofpoint News Feed
N
News | PayPal Newsroom
www.infosecurity-magazine.com
www.infosecurity-magazine.com
爱范儿
爱范儿
O
OpenAI News
酷 壳 – CoolShell
酷 壳 – CoolShell
月光博客
月光博客
Martin Fowler
Martin Fowler
Engineering at Meta
Engineering at Meta
D
Docker
Y
Y Combinator Blog
博客园 - 聂微东
G
Google Developers Blog
S
Security @ Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
阮一峰的网络日志
阮一峰的网络日志
C
CXSECURITY Database RSS Feed - CXSecurity.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
CERT Recently Published Vulnerability Notes
I
Intezer
G
GRAHAM CLULEY
有赞技术团队
有赞技术团队
Attack and Defense Labs
Attack and Defense Labs
V
Visual Studio Blog
博客园 - Franky
博客园 - 三生石上(FineUI控件)
W
WeLiveSecurity
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hugging Face - Blog
Hugging Face - Blog
Scott Helme
Scott Helme
T
Troy Hunt's Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 最新话题
C
Cybersecurity and Infrastructure Security Agency CISA

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
JavaScript Promises Explained for Beginners
Pratham · 2026-05-10 · via DEV Community

The cure for callback hell — and a cleaner way to handle things that take time.


In the last article, we talked about callbacks and saw how they can spiral into deeply nested, hard-to-read code — the infamous "Pyramid of Doom." If you've ever looked at five levels of indented callbacks and thought "there has to be a better way," you're right. There is.

Promises are that better way. They take the same asynchronous operations — fetching data, reading files, waiting for timers — and give you a flat, readable chain instead of a nested pyramid. Same results, dramatically better code.

When I first encountered Promises in the ChaiCode Web Dev Cohort 2026, I'll be honest — the concept felt abstract. "A future value?" "Pending, fulfilled, rejected?" But once I wrote a few .then() chains and compared them to the callback versions, the improvement was so obvious I never wanted to go back.

Let me show you.


What Problem Do Promises Solve?

Let's start with the pain. Here's a callback-based approach to a common pattern: fetch a user, then their orders, then shipping details.

// Callback version — the Pyramid of Doom
getUser(1, (err, user) => {
  if (err) return console.log(err);

  getOrders(user.id, (err, orders) => {
    if (err) return console.log(err);

    getShipping(orders[0].id, (err, shipping) => {
      if (err) return console.log(err);

      console.log(`Shipping to: ${shipping.address}`);
    });
  });
});

Enter fullscreen mode Exit fullscreen mode

Problems: deep nesting, repeated error handling, hard to read, hard to maintain.

Now here's the same thing with Promises:

// Promise version — flat and readable
getUser(1)
  .then((user) => getOrders(user.id))
  .then((orders) => getShipping(orders[0].id))
  .then((shipping) => console.log(`Shipping to: ${shipping.address}`))
  .catch((err) => console.log(err));

Enter fullscreen mode Exit fullscreen mode

Same steps. Same logic. But flat, linear, and with one catch handling all errors. That's the problem Promises solve.


What Is a Promise?

A Promise is an object that represents a value that might not be available yet but will be at some point in the future — or it might fail.

Think of it like ordering food online:

  1. You place the order → you get a receipt (the promise). The food isn't here yet, but you have a guarantee that it will arrive or you'll be notified of a problem.
  2. Your order is being prepared → the promise is pending.
  3. Food arrives → the promise is fulfilled (success!).
  4. Something goes wrong (restaurant closed, wrong address) → the promise is rejected (failure).
Online Order Analogy:

  Place order  →  Pending...  →  Fulfilled (food arrives! 🍕)
                                 OR
                              →  Rejected (order failed ❌)

Enter fullscreen mode Exit fullscreen mode

In code, a Promise works the same way: it starts in a pending state, and eventually settles as either fulfilled (with a value) or rejected (with an error).


Promise States

Every Promise has exactly three possible states:

State Meaning Settled?
Pending Operation hasn't completed yet ❌ No
Fulfilled Operation succeeded — result is available ✅ Yes
Rejected Operation failed — error is available ✅ Yes

A Promise moves from pending to either fulfilled or rejected — never both, and never back to pending.

Promise Lifecycle Diagram

┌──────────────────────────────────────────────────┐
│                                                  │
│   new Promise((resolve, reject) => { ... })      │
│                                                  │
│                    ┌─────────┐                   │
│                    │ PENDING │                   │
│                    └────┬────┘                   │
│                         │                        │
│              ┌──────────┴──────────┐             │
│              ↓                     ↓             │
│       ┌────────────┐        ┌───────────┐        │
│       │ FULFILLED  │        │ REJECTED  │        │
│       │            │        │           │        │
│       │ resolve()  │        │ reject()  │        │
│       │ called     │        │ called    │        │
│       └──────┬─────┘        └─────┬─────┘        │
│              ↓                    ↓              │
│          .then()              .catch()           │
│       handles the          handles the           │
│       success value        error reason          │
│                                                  │
└──────────────────────────────────────────────────┘

Once settled (fulfilled or rejected), a promise NEVER changes state again.

Enter fullscreen mode Exit fullscreen mode


Creating a Basic Promise

Here's the syntax for creating a Promise from scratch:

const myPromise = new Promise((resolve, reject) => {
  // Do some async work here...

  // If successful:
  resolve("Success! Here's your data.");

  // If something goes wrong:
  // reject("Something failed.");
});

Enter fullscreen mode Exit fullscreen mode

  • resolve(value) — call this when the operation succeeds. The promise becomes fulfilled with this value.
  • reject(reason) — call this when the operation fails. The promise becomes rejected with this reason.

Example: Simulating an API Call

const fetchUser = (userId) => {
  return new Promise((resolve, reject) => {
    console.log(`Fetching user ${userId}...`);

    setTimeout(() => {
      if (userId > 0) {
        resolve({ id: userId, name: "Pratham", role: "developer" });
      } else {
        reject("Invalid user ID!");
      }
    }, 2000);
  });
};

Enter fullscreen mode Exit fullscreen mode

This function returns a Promise. After 2 seconds:

  • If userId is valid → resolved with user data
  • If userId is invalid → rejected with an error message

Handling Success and Failure

.then() — Handle Fulfilled Promises

fetchUser(1).then((user) => {
  console.log(`Got user: ${user.name}`);
});
// (after 2 seconds) "Got user: Pratham"

Enter fullscreen mode Exit fullscreen mode

.then() receives the value that resolve() was called with.

.catch() — Handle Rejected Promises

fetchUser(-1).catch((error) => {
  console.log(`Error: ${error}`);
});
// (after 2 seconds) "Error: Invalid user ID!"

Enter fullscreen mode Exit fullscreen mode

.catch() receives the reason that reject() was called with.

Using Both Together

fetchUser(1)
  .then((user) => {
    console.log(`✅ User: ${user.name} (${user.role})`);
  })
  .catch((error) => {
    console.log(`❌ Failed: ${error}`);
  });

Enter fullscreen mode Exit fullscreen mode

If the promise is fulfilled, .then() runs. If it's rejected, .catch() runs. Only one will execute — never both.

.finally() — Run No Matter What

fetchUser(1)
  .then((user) => console.log(`User: ${user.name}`))
  .catch((error) => console.log(`Error: ${error}`))
  .finally(() => console.log("Request complete — cleanup done."));

Enter fullscreen mode Exit fullscreen mode

.finally() runs whether the promise succeeded or failed. Perfect for cleanup tasks like hiding loading spinners.


The Promise Lifecycle in Action

Let me trace through the complete lifecycle with a real example:

console.log("1. Starting...");

const order = new Promise((resolve, reject) => {
  console.log("2. Promise created — cooking pizza... 🍕");

  setTimeout(() => {
    const success = true;

    if (success) {
      resolve("Margherita Pizza");
    } else {
      reject("Kitchen is closed!");
    }
  }, 3000);
});

console.log("3. Doing other things while waiting...");

order
  .then((pizza) => {
    console.log(`4. Order fulfilled: ${pizza} delivered! 🎉`);
  })
  .catch((reason) => {
    console.log(`4. Order rejected: ${reason} 😞`);
  });

console.log("5. More synchronous code...");

Enter fullscreen mode Exit fullscreen mode

Output:

1. Starting...
2. Promise created — cooking pizza... 🍕
3. Doing other things while waiting...
5. More synchronous code...
4. Order fulfilled: Margherita Pizza delivered! 🎉   ← 3 seconds later

Enter fullscreen mode Exit fullscreen mode

Trace

Time 0ms:
  "1. Starting..." — synchronous, runs immediately
  Promise constructor runs — "2. Promise created..." — synchronous!
  setTimeout registered (3-second timer starts)
  "3. Doing other things..." — synchronous
  .then() registered — "I'll call this function when the promise resolves"
  "5. More synchronous code..." — synchronous

Time 3000ms:
  Timer fires → resolve("Margherita Pizza") → promise is FULFILLED
  .then() callback executes → "4. Order fulfilled: ..."

Enter fullscreen mode Exit fullscreen mode

Key insight: The Promise constructor runs synchronously. Only the .then() and .catch() callbacks are deferred until the promise settles.


Promise Chaining

This is where Promises truly shine. Each .then() returns a new Promise, which means you can chain them — one after another, flat and readable.

How Chaining Works

const getUser = (id) =>
  new Promise((resolve) => {
    setTimeout(() => resolve({ id, name: "Pratham" }), 500);
  });

const getOrders = (userId) =>
  new Promise((resolve) => {
    setTimeout(() => resolve([{ id: 101, item: "Laptop" }]), 500);
  });

const getShipping = (orderId) =>
  new Promise((resolve) => {
    setTimeout(() => resolve({ address: "Delhi, India" }), 500);
  });

// Chained — each .then() passes its result to the next
getUser(1)
  .then((user) => {
    console.log(`User: ${user.name}`);
    return getOrders(user.id);
  })
  .then((orders) => {
    console.log(`Order: ${orders[0].item}`);
    return getShipping(orders[0].id);
  })
  .then((shipping) => {
    console.log(`Ship to: ${shipping.address}`);
  })
  .catch((error) => {
    console.log(`Error at any step: ${error}`);
  });

// User: Pratham
// Order: Laptop
// Ship to: Delhi, India

Enter fullscreen mode Exit fullscreen mode

Chaining Flow Visual

getUser(1)
    
     resolves with user
.then(user => getOrders(user.id))
    
     resolves with orders
.then(orders => getShipping(orders[0].id))
    
     resolves with shipping
.then(shipping => console.log(shipping.address))

    If ANY step fails:
    
.catch(error => handle it)

FLAT. LINEAR. ONE ERROR HANDLER.

Enter fullscreen mode Exit fullscreen mode

Compare this to the nested callback version — same three steps, but without the pyramid:

Callbacks:                          Promises:

getUser(1, (err, user) => {         getUser(1)
  getOrders(user.id, (err, o) => {    .then(user => getOrders(user.id))
    getShipping(o[0].id, (err, s) =>  .then(orders => getShipping(...))
      console.log(s.address)          .then(ship => console.log(...))
    });                               .catch(err => console.log(err));
  });
});

Nested, messy, error-prone         Flat, clean, one catch

Enter fullscreen mode Exit fullscreen mode


Callback vs Promise — The Comparison

Feature Callbacks Promises
Readability Nested → hard to follow Flat chain → easy to read
Error handling Every level needs if (err) One .catch() for the entire chain
Composability Difficult to combine .then() chains naturally
Return values Can't return — must pass forward Each .then() returns a new Promise
State tracking No built-in state Pending → Fulfilled / Rejected
Debugging Hard to trace through nesting Clear, linear flow

Promises don't add new capabilities — everything you can do with Promises, you could technically do with callbacks. But Promises make the code dramatically cleaner, more maintainable, and less error-prone.


Common Mistakes

1. Forgetting to Return in .then()

// ❌ Wrong — missing return
getUser(1)
  .then((user) => {
    getOrders(user.id); // Not returned! Chain breaks here.
  })
  .then((orders) => {
    console.log(orders); // undefined!
  });

// ✅ Correct — return the Promise
getUser(1)
  .then((user) => {
    return getOrders(user.id);
  })
  .then((orders) => {
    console.log(orders); // Works!
  });

Enter fullscreen mode Exit fullscreen mode

2. Nesting Promises (Defeating the Purpose)

// ❌ Don't do this — you're back to callback hell
getUser(1).then((user) => {
  getOrders(user.id).then((orders) => {
    getShipping(orders[0].id).then((shipping) => {
      console.log(shipping.address);
    });
  });
});

// ✅ Do this — flat chain
getUser(1)
  .then((user) => getOrders(user.id))
  .then((orders) => getShipping(orders[0].id))
  .then((shipping) => console.log(shipping.address))
  .catch((err) => console.log(err));

Enter fullscreen mode Exit fullscreen mode

3. Not Adding .catch()

// ❌ Unhandled rejection — will cause warnings/errors
getUser(-1).then((user) => console.log(user));

// ✅ Always handle errors
getUser(-1)
  .then((user) => console.log(user))
  .catch((err) => console.log("Handled:", err));

Enter fullscreen mode Exit fullscreen mode


Let's Practice: Hands-On Assignment

Part 1: Create a Basic Promise

const coinFlip = new Promise((resolve, reject) => {
  const result = Math.random() > 0.5;

  setTimeout(() => {
    if (result) {
      resolve("Heads! You win! 🎉");
    } else {
      reject("Tails! You lose. 😅");
    }
  }, 1000);
});

coinFlip
  .then((message) => console.log(message))
  .catch((message) => console.log(message))
  .finally(() => console.log("Game over."));

Enter fullscreen mode Exit fullscreen mode

Part 2: Chain Promises

const step1 = () =>
  new Promise((resolve) => {
    setTimeout(() => {
      console.log("Step 1: Data fetched");
      resolve("raw data");
    }, 1000);
  });

const step2 = (data) =>
  new Promise((resolve) => {
    setTimeout(() => {
      console.log(`Step 2: Processing ${data}`);
      resolve("processed data");
    }, 1000);
  });

const step3 = (data) =>
  new Promise((resolve) => {
    setTimeout(() => {
      console.log(`Step 3: Saving ${data}`);
      resolve("saved successfully");
    }, 1000);
  });

step1()
  .then((result) => step2(result))
  .then((result) => step3(result))
  .then((result) => console.log(`Done: ${result}`))
  .catch((err) => console.log(`Error: ${err}`));

Enter fullscreen mode Exit fullscreen mode

Part 3: Handle Errors in a Chain

const riskyOperation = (name) =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      if (name.length > 0) {
        resolve(`${name} processed successfully!`);
      } else {
        reject("Empty name — operation failed!");
      }
    }, 500);
  });

// Successful
riskyOperation("Pratham")
  .then((msg) => console.log(`✅ ${msg}`))
  .catch((err) => console.log(`❌ ${err}`));

// Failed
riskyOperation("")
  .then((msg) => console.log(`✅ ${msg}`))
  .catch((err) => console.log(`❌ ${err}`));

Enter fullscreen mode Exit fullscreen mode


Key Takeaways

  1. Promises solve callback hell by replacing nested callbacks with flat, chainable .then() calls and centralized error handling with .catch().
  2. A Promise has three states: pending (waiting), fulfilled (success via resolve()), and rejected (failure via reject()). Once settled, it never changes.
  3. .then() handles success. .catch() handles failure. .finally() runs regardless. Together they cover every outcome.
  4. Promise chaining works because each .then() returns a new Promise. Always return inside .then() to keep the chain going.
  5. Promises don't add new capabilities over callbacks — they add structure, readability, and maintainability to async code.

Wrapping Up

Promises were the moment async JavaScript stopped being painful and started being elegant. The same operations, the same logic, but expressed in a way that reads top-to-bottom instead of nesting inward. And once you're comfortable with Promises, the next step — async/await — makes the syntax even cleaner by letting you write async code that looks synchronous.

I'm learning all of this through the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg. Promises were one of those topics where I went from "this is confusing" to "this is beautiful" in the span of a single lesson. If callbacks made sense to you, Promises will feel like a natural upgrade.

Connect with me on LinkedIn or visit PrathamDEV.in. More articles on the way.

Happy coding! 🚀


Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode