当前位置: 首页 > news >正文

TypeScript/JavaScript 中的异步迭代语句

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 消息等场景。

http://www.jsqmd.com/news/351117/

相关文章:

  • 一文读懂:传统RAG、多模态RAG与Agent的本质区别与联系,收藏级技术解析
  • 基于SpringBoot + Vue的自驾游攻略查询系统
  • 微信小程序Python-uniapp儿童疫苗接种预约医疗提醒系统
  • CANN生态深度解析:ops-nn仓库的算子实现与性能优化
  • 【收藏必备】颠覆Skills!新型Agent自己造工具开源,零技能起步性能碾压Gemini 3 Pro
  • 速看!AI应用架构师如何运用AI驱动质量管理降本增效
  • js中的生成器函数
  • SAP核心模块单据关系及关键数据表详解
  • 微信小程序Python-uniapp基于Android的全民健身App设计与实现
  • 地平线征程 6 工具链入门教程 | 征程 6B 计算平台部署指南
  • 微信小程序Python-uniapp 小区果蔬商城
  • Vibe Coding 与 LangChain、LangGraph 的协同进化
  • 代码生成超越 GPT-4:DeepSeek-V4 编程任务实战与 2026 开发者效率提升指南
  • 微信小程序Python-uniapp 游戏攻略系统 逃跑吧!少年的游戏角色介绍系统
  • 【毕设】基于人脸识别的实验室智能门禁系统的设计与实现
  • 微信小程序Python-uniapp 演唱会售票系统
  • 2026低成本训练趋势:DeepSeek复刻V4训练管线,低成本实现模型微调实战
  • 大数据领域Zookeeper的会话管理机制研究
  • AI原生应用架构设计:何时使用模型蒸馏?
  • 微信小程序Python-uniapp 智能包裹配送服务管理系统
  • 图解网络26 - 指南
  • 微信小程序Python-uniapp 校园财递通快递代取系统的设计与实现
  • 微信小程序Python-uniapp 消防知识学习平台系统
  • DeepSeek总结的PostgreSQL解码GIF文件SQL移植到DuckDB的性能优化方法
  • 基于Spring Boot的企业采购管理系统的设计与实现
  • 如何通过管理中心发布Teams应用
  • holiday 2026.02.06
  • 比较好的入户门品牌有哪些?2026十大品牌综合实力深度评测解析 - 匠言榜单
  • 数据行业六大岗位详解+AI大模型入门到进阶学习路线_AI大模型时代下的数据行业
  • AI大模型高薪职位全攻略+学习资料包,助程序员薪资翻倍,从入门到实战_AI大模型岗位薪资揭秘:2026大模型岗位薪资