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

推荐订阅源

U
Unit 42
C
Cybersecurity and Infrastructure Security Agency CISA
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Know Your Adversary
Know Your Adversary
S
Securelist
I
Intezer
AWS News Blog
AWS News Blog
L
LINUX DO - 热门话题
P
Privacy International News Feed
Recent Announcements
Recent Announcements
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 聂微东
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
The GitHub Blog
The GitHub Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Schneier on Security
Schneier on Security
N
Netflix TechBlog - Medium
爱范儿
爱范儿
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
CERT Recently Published Vulnerability Notes
Hacker News: Ask HN
Hacker News: Ask HN
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
Blog — PlanetScale
Blog — PlanetScale
WordPress大学
WordPress大学
S
Secure Thoughts
K
Kaspersky official blog
N
News | PayPal Newsroom
O
OpenAI News
Last Week in AI
Last Week in AI
C
Check Point Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tor Project blog
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
D
Docker
Hugging Face - Blog
Hugging Face - Blog
T
Threat Research - Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
The Register - Security
The Register - Security
博客园 - 司徒正美
Martin Fowler
Martin Fowler
人人都是产品经理
人人都是产品经理
P
Palo Alto Networks Blog

博客园 - 悠哉大斌

AI Agent 安全沙箱技术对比:E2B、Cube Sandbox 与 Docker Sandboxes linux 升级 claude code的坑 debian(WSL) apt 代理配置 linux内核之Namespaces、Cgroups、Capabilities、Seccomp和Landlock 大语言模型推理中的隐藏瓶颈及其解决方法 Docker Sandboxes 技术是什么,和docker容器有什么区别 什么是 Docker Agent以及一个Docker Agent示例 windows wsl 安装 Temurin® JDK claude Code 和 codex 作为编程代理,前者使用typescript开发,后者使用rust,他们的决策依据是什么 Java 并发编程发展史与 java.util.concurrent 全景解析 LLM 真的改变了编码风格吗? 如果人工智能会犯错且不精确,为什么它正在改变世界? Python 的协程模型和 JavaScript 的 async/await python闭包和function.__closure__特殊属性 python 的 dunder name和 sunder name 基于nodejs设计REST API的知名开源框架 windows上使用node-oracledb Thick 模式连接 Oracle 11g Claude Code CLI连接 DeepSeek V4模型后调用报400错误 python里对象(object)到底是什么 Python 泛型演变史 Python 类型别名的演变 Python 类型提示的演变史 PEP 593 新增的Annotated 类型 Alibaba AgentScope 和 microsoft agent framework 详细对比分析 spring AI Alibaba Agent Framework 和 agentscope有什么区别和联系 AI Agent协作模式以及主流开源框架对协作模式的支持 Tailscale 是如何接管 DNS 的? Agent = Model + Harness 使用rust编写typescript编译器的难点在什么地方,哪些数据结构是rust不擅长的? js中的生成器函数 Tailscale Serve and Funnel openclaw gateway的网络绑定模式 websocket协议和http协议有何依赖关系? MCP通信的双方是谁? claude code MCP 安装范围 如何在wsl2环境下给claude code cli 配置 playwright-mcp wsl的网络模式有哪几种,有哪些区别? AI Agent memory是什么? ai agent skills是什么? Go测试生态系统工具与最佳实践深度调研(聚焦认证授权系统) 线性代数中常见矩阵类型的概念关系思维导图 三种主流授权策略
TypeScript/JavaScript 中的异步迭代语句
悠哉大斌 · 2026-02-06 · via 博客园 - 悠哉大斌

for await...of 是 TypeScript/JavaScript 中的异步迭代语句,专门用于遍历异步可迭代对象(Async Iterable)。

基本语法

for await (const item of asyncIterable) {
  // 处理每个异步获取的值
}

与普通 for...of 的区别

特性 for...of for await...of
迭代对象 同步可迭代对象 异步可迭代对象
返回值 同步值 Promise 解析后的值
使用场景 数组、Map、Set等 异步流、生成器等

使用场景

1. 处理异步生成器函数

async function* asyncGenerator() {
  yield await Promise.resolve(1);
  yield await Promise.resolve(2);
  yield await Promise.resolve(3);
}

async function process() {
  for await (const value of asyncGenerator()) {
    console.log(value); // 1, 2, 3
  }
}

2. 处理多个 Promise 的集合

async function fetchUrls(urls: string[]) {
  for await (const response of urls.map(url => fetch(url))) {
    const data = await response.json();
    console.log(data);
  }
}

3. Node.js 流处理

import { createReadStream } from 'fs';
import { createInterface } from 'readline';

async function readLargeFile() {
  const fileStream = createReadStream('large-file.txt');
  const rl = createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });

  for await (const line of rl) {
    console.log(line); // 逐行处理大文件
  }
}

4. Web Streams API

async function processStream(stream: ReadableStream) {
  const reader = stream.getReader();
  
  try {
    for await (const chunk of stream) {
      console.log('Received chunk:', chunk);
    }
  } finally {
    reader.releaseLock();
  }
}

实际示例:批量处理异步任务

// 模拟异步数据源
async function* fetchPaginatedData(pageSize: number = 10) {
  let page = 0;
  let hasMore = true;
  
  while (hasMore) {
    // 模拟 API 调用
    const data = await fetchDataFromAPI(page, pageSize);
    yield data.items;
    
    hasMore = data.hasMore;
    page++;
  }
}

async function processAllData() {
  const results = [];
  
  for await (const items of fetchPaginatedData()) {
    // 等待所有项目的处理完成
    const processed = await Promise.all(
      items.map(async item => processItem(item))
    );
    results.push(...processed);
  }
  
  return results;
}

注意事项

  1. 必须在 async 函数中使用

    // ❌ 错误:不能在同步函数中使用
    function syncFunction() {
      for await (const item of asyncIterable) { ... }
    }
    
    // ✅ 正确:必须在 async 函数中
    async function asyncFunction() {
      for await (const item of asyncIterable) { ... }
    }
    
  2. 错误处理

    async function processWithErrorHandling() {
      try {
        for await (const item of asyncIterable) {
          // 处理每个项目
        }
      } catch (error) {
        console.error('迭代过程中出错:', error);
      }
    }
    
  3. 与 Promise.all() 的区别

    • for await...of:顺序处理,等待前一个完成
    • Promise.all():并行处理,等待所有完成

底层原理

for await...of 实际上是对异步迭代器的语法糖:

// for await...of 的等价实现
async function manualAsyncIteration(asyncIterable) {
  const iterator = asyncIterable[Symbol.asyncIterator]();
  
  try {
    while (true) {
      const { value, done } = await iterator.next();
      if (done) break;
      // 使用 value
    }
  } finally {
    if (iterator.return) await iterator.return();
  }
}

浏览器和 Node.js 支持

  • ES2018+ 标准
  • Node.js 10.0.0+ 完全支持
  • 现代浏览器支持(除 IE 外)

for await...of 是处理异步数据流的强大工具,特别适合处理分页 API、文件流、WebSocket 消息等场景。