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

推荐订阅源

AI
AI
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
云风的 BLOG
云风的 BLOG
Recorded Future
Recorded Future
Apple Machine Learning Research
Apple Machine Learning Research
F
Fortinet All Blogs
罗磊的独立博客
爱范儿
爱范儿
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
D
Docker
C
CXSECURITY Database RSS Feed - CXSecurity.com
Spread Privacy
Spread Privacy
Recent Announcements
Recent Announcements
酷 壳 – CoolShell
酷 壳 – CoolShell
G
GRAHAM CLULEY
A
About on SuperTechFans
C
Cisco Blogs
The Register - Security
The Register - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog
Project Zero
Project Zero
V
V2EX
K
Kaspersky official blog
P
Privacy International News Feed
博客园 - 叶小钗
I
Intezer
T
Threatpost
The GitHub Blog
The GitHub Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
V
Vulnerabilities – Threatpost
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
Cyberwarzone
Cyberwarzone
Microsoft Azure Blog
Microsoft Azure Blog
N
Netflix TechBlog - Medium
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 【当耐特】
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
F
Full Disclosure
The Cloudflare Blog
P
Palo Alto Networks Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Tenable Blog

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, Async/Await, and Error Handling: The Complete Guide (2026)
Alex Chen · 2026-05-28 · via DEV Community

Alex Chen

JavaScript Promises, Async/Await, and Error Handling: The Complete Guide (2026)

Async code doesn't have to be confusing. Master these patterns and you'll handle any async scenario.

The Evolution of Async in JavaScript

Callback Hell → Promises → Async/Await → Top-level Await

Each step solved real problems:
→ Callbacks: No composition, nesting nightmare
→ Promises: Composable but still .then() chains
→ Async/Await: Reads like synchronous code
→ Top-level Await: Use await in modules (Node.js 14+)

Callbacks: Where It Started

// The old way (still used in Node.js core APIs)
const fs = require('fs');

// ❌ Callback hell (pyramid of doom)
fs.readFile('file1.txt', 'utf8', (err, data1) => {
  if (err) return console.error(err);
  fs.readFile('file2.txt', 'utf8', (err, data2) => {
    if (err) return console.error(err);
    fs.writeFile('output.txt', data1 + data2, (err) => {
      if (err) return console.error(err);
      console.log('Done!');
    });
  });
});

// Problems:
// → Error handling repeated at every level
// → Deeply nested, hard to read
// → Can't easily compose multiple async operations
// → Control flow is inverted (you don't call, you get called)

Promises: The Foundation

Creating Promises

// Basic promise creation
function fetchData(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(xhr.responseText);
      } else {
        reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
      }
    };
    xhr.onerror = () => reject(new Error('Network error'));
    xhr.send();
  });
}

// Promise states:
// → Pending: Initial state, neither fulfilled nor rejected
// → Fulfilled: Operation completed successfully (has a value)
// → Rejected: Operation failed (has a reason/error)
// → Settled: Either fulfilled or rejected (final state)

// Once settled, a promise CANNOT change state again.
// This immutability is the key to reliable async code.

Consuming Promises

fetchData('https://api.example.com/data')
  .then(data => {
    console.log('Got:', data);
    return JSON.parse(data); // Return value becomes next .then()'s input
  })
  .then(parsed => {
    console.log('Parsed:', parsed);
    return parsed.items; // Pass only items to next handler
  })
  .then(items => {
    console.log(`Found ${items.length} items`);
    return processItems(items); // Returns another Promise!
  })
  .catch(error => {           // Catches ANY rejection in the chain
    console.error('Something failed:', error.message);
    // If you want the chain to continue, return a value here
    return []; // Fallback value
  })
  .finally(() => {            // ALWAYS runs, regardless of success/failure
    console.log('Request complete');
    loadingIndicator.hide();   // Cleanup code goes here
  });

// Key insight: .catch() is also a .then(undefined, onRejected)
// So it returns a new Promise, allowing chaining to continue!

Common Promise Patterns

// Pattern 1: Parallel execution (all start immediately)
Promise.all([
  fetchUser(userId),
  fetchOrders(userId),
  fetchPreferences(userId),
])
  .then(([user, orders, prefs]) => {
    // All resolved! Data arrives in order.
    renderDashboard({ user, orders, prefs });
  })
  .catch(err => {
    // ANY one rejects → entire Promise.all rejects
    console.error('Failed to load dashboard:', err);
  });

// Pattern 2: Race (first to settle wins)
const timeout = new Promise((_, reject) =>
  setTimeout(() => reject(new Error('Timeout')), 5000)
);

Promise.race([fetchData(url), timeout])
  .then(data => console.log(data))
  .catch(err => console.error(err)); // Could be timeout OR fetch error

// Pattern 3: AllSettled (wait for ALL, collect results/errors)
Promise.allSettled([
  fetch('/api/a'),
  fetch('/api/b'),
  fetch('/api/c'), // This might fail
])
  .then(results => {
    results.forEach((result, i) => {
      if (result.status === 'fulfilled') {
        console.log(`API ${i}:`, result.value);
      } else {
        console.warn(`API ${i} failed:`, result.reason);
      }
    });
  });

// Pattern 4: Any (first SUCCESS wins)
Promise.any([
  fetchFromPrimary(url),
  fetchFromBackup(url),
  fetchFromCache(url),
])
  .then(data => console.log('Got data from somewhere!'))
  .catch(err => {
    // All rejected (AggregateError with all reasons)
    console.error('All sources failed');
  });

// Pattern 5: Sequential execution (each waits for previous)
async function processItemsSequentially(items) {
  const results = [];
  for (const item of items) {
    const result = await processItem(item); // Wait for each
    results.push(result);
  }
  return results;
}

// vs parallel (all at once):
async function processItemsParallel(items) {
  return Promise.all(items.map(item => processItem(item)));
}

Async/Await: Syntactic Sugar That Changes Everything

Basic Syntax

// async function ALWAYS returns a Promise
async function getUser(id) {
  // Inside async functions, use await instead of .then()
  const response = await fetch(`/api/users/${id}`);
  const user = await response.json();

  // This reads TOP TO BOTTOM like synchronous code!
  // No nesting, no .then() chains, no callback pyramids

  return user;
  // Implicitly wrapped in Promise.resolve(user)
}

// Calling an async function always returns a Promise
getUser(123).then(user => console.log(user));

// You can also destructure the await:
const { name, email } = await getUser(123);

// Works in arrow functions too:
const getData = async () => {
  const res = await fetch('/data');
  return res.json();
};

Error Handling with Try/Catch

// This is where async/await REALLY shines over .then().catch()
async function robustFetch(url) {
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000);

    const response = await fetch(url, { signal: controller.signal });
    clearTimeout(timeoutId);

    if (!response.ok) {
      // HTTP errors (4xx, 5xx) do NOT reject! Handle explicitly.
      const errorBody = await response.json().catch(() => ({}));
      throw new FetchError(
        `HTTP ${response.status}: ${response.statusText}`,
        response.status,
        errorBody
      );
    }

    return await response.json();

  } catch (error) {
    if (error.name === 'AbortError') {
      throw new FetchError('Request timed out', 408);
    }
    if (error.code === 'ECONNREFUSED') {
      throw new FetchError('Server unreachable', 503);
    }
    // Re-throw unknown errors
    throw error;
  }
}

class FetchError extends Error {
  constructor(message, status, body) {
    super(message);
    this.name = 'FetchError';
    this.status = status;
    this.body = body;
  }
}

// Usage:
try {
  const data = await robustFetch('/api/data');
  console.log(data);
} catch (error) {
  if (error instanceof FetchError) {
    if (error.status === 408) showTimeoutMessage();
    else if (error.status === 404) showNotFound();
    else showError(error.message);
  } else {
    showError('Unexpected error');
  }
}

Advanced Patterns

// Pattern 1: Retry with exponential backoff
async function retry(fn, maxAttempts = 3, baseDelay = 1000) {
  let lastError;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
      if (attempt < maxAttempts) {
        const delay = baseDelay * Math.pow(2, attempt - 1); // 1s, 2s, 4s
        console.warn(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
        await sleep(delay);
      }
    }
  }
  throw lastError; // All attempts exhausted
}

function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }

// Usage:
const data = await retry(() => fetchAPI('/expensive-operation'));

// Pattern 2: Concurrent with concurrency limit
async function concurrentMap(items, fn, concurrency = 5) {
  const results = [];
  let index = 0;

  async function worker() {
    while (index < items.length) {
      const currentIndex = index++;
      results[currentIndex] = await fn(items[currentIndex], currentIndex);
    }
  }

  const workers = Array.from({ length: Math.min(concurrency, items.length) }, worker);
  await Promise.all(workers);
  return results;
}

// Process 100 API calls, 5 at a time:
const results = await concurrentMap(urls, url => fetch(url).then(r => r.json()), 5);

// Pattern 3: Request caching (deduplicate in-flight requests)
const pendingRequests = new Map();

function cachedFetch(url) {
  if (pendingRequests.has(url)) {
    return pendingRequests.get(url); // Return existing Promise
  }

  const promise = fetch(url)
    .then(res => res.json())
    .finally(() => pendingRequests.delete(url));

  pendingRequests.set(url, promise);
  return promise;
}

// Multiple components can call cachedFetch simultaneously,
// but only ONE actual network request is made.

// Pattern 4: Timeout wrapper
async function withTimeout(promise, ms, message = 'Operation timed out') {
  const timer = new Promise((_, reject) =>
    setTimeout(() => reject(new Error(message)), ms)
  );
  return Promise.race([promise, timer]);
}

// Usage:
const user = await withTimeout(fetchUser(id), 3000, 'User lookup timed out');

// Pattern 5: Async iterator (for streaming/pagination)
async function* paginate(endpoint, pageSize = 50) {
  let page = 1;
  while (true) {
    const response = await fetch(`${endpoint}?page=${page}&size=${pageSize}`);
    const { items, hasMore } = await response.json();

    yield* items; // Yield each item individually

    if (!hasMore || items.length === 0) break;
    page++;
  }
}

// Usage with for-await-of:
for await (const item of paginate('/api/users')) {
  console.log(item.name);
  // Processes items as they arrive, not after ALL pages load
}

Common Mistakes & Anti-Patterns

// ❌ Mistake 1: Forgetting await in loops
// This fires ALL requests simultaneously without waiting:
urls.forEach(async url => {
  const data = await fetch(url); // Each runs independently
  processData(data);
});
// Fix: Use for...of or Promise.all

// ❌ Mistake 2: Fire-and-forget (unhandled promise rejection)
async function updateUser(id) {
  await fetch(`/api/users/${id}`, { method: 'PATCH', body: {...} });
  // What if this fails? Silent failure!
}
updateUser(123); // No .catch(), no await → unhandled rejection!

// Fix: Always handle or at least suppress intentionally:
updateUser(123).catch(console.error);

// ❌ Mistake 3: Unnecessary async
async function getValue() {
  return 42; // Wrapping synchronous value in Promise unnecessarily
}
// Fix: Just return the value directly (unless API requires Promise)

// ❌ Mistake 4: try/catch around everything
try {
  const a = await syncFunction(); // Not needed for sync code
  const b = await anotherSync();
} catch (e) { ... }

// ❌ Mistake 5: Mixing callbacks and promises
fs.readFile('file.txt', (err, data) => {
  // Now you're back in callback land inside an async function
});

// Fix: Use fs.promises (or util.promisify):
import { readFile } from 'fs/promises';
const data = await readFile('file.txt', 'utf8'); // Clean!

// ❌ Mistake 6: Awaiting inside map without returning promises
const results = items.map(async item => {
  return await process(item); // Returns array of Promises, NOT results!
});
// results is [Promise, Promise, ...] not [result, result, ...]

// Fix: Use Promise.all:
const results = await Promise.all(items.map(item => process(item)));

Performance Tips

// Tip 1: Parallel > Sequential when order doesn't matter
// Slow: Each request waits for the previous
const a = await fetchA();
const b = await fetchB();
const c = await fetchC();

// Fast: All fire at once
const [a, b, c] = await Promise.all([fetchA(), fetchB(), fetchC()]);
// Total time = max(a, b, c) instead of a + b + c

// Tip 2: Don't await outside try/catch if you want partial success
const results = await Promise.allSettled(
  items.map(item => riskyOperation(item))
);
const successes = results.filter(r => r.status === 'fulfilled').map(r => r.value);
const failures = results.filter(r => r.status === 'rejected').map(r => r.reason);

// Tip 3: Lazy evaluation for expensive operations
function lazyAsync(fn) {
  let cache;
  return () => cache ??= fn(); // Compute once, reuse forever
}

const heavyData = lazyAsync(() => fetchExpensiveData());
// Only actually fetches when first awaited

// Tip 4: Use AbortController for cancellable operations
function cancellableFetch(url, signal) {
  return fetch(url, { signal }); // Pass signal through
}

const controller = new AbortController();
const promise = cancellableFetch(url, controller.signal);

// Later, if user navigates away:
controller.abort(); // Cancels the fetch!

// Tip 5: Batch small operations
async function batchWrite(items, batchSize = 10) {
  for (let i = 0; i < items.length; i += batchSize) {
    const batch = items.slice(i, i + batchSize);
    await db.batchInsert(batch); // One DB round-trip per batch
  }
}


What's your favorite async pattern? Which one took you longest to understand?

Follow @armorbreak for more practical developer guides.