元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
执行上下文
▶
创建过程
变量对象
作用域链
This绑定
▶
执行阶段
执行栈机制
词法环境
闭包实现
▶
内存管理
▶
内存模型
堆栈结构
内存分配
内存泄漏
▶
回收机制
标记清除
引用计数
代际假说
▶
事件循环
▶
运行机制
调用栈解析
任务队列
微任务优先
▶
异步处理
Promise原理
Async/Await
Web Workers
▶
原型系统
▶
原型基础
原型链机制
__proto__属性
构造函数
▶
类继承
ES6类语法
继承实现
super关键字
▶
类型系统
▶
基础类型
类型检测
装箱拆箱
类型转换
▶
高级类型
Symbol特性
BigInt实现
类型数组
▶
作用域与闭包
▶
作用域体系
词法作用域
动态作用域
作用域链生成
▶
闭包机制
闭包存储结构
IIFE模式原理
内存泄漏防范
发布时间:
2025-03-22 11:39
↑
☰
# JavaScript Async/Await机制 Async/Await是JavaScript中处理异步操作的语法糖,建立在Promise之上。本文将深入讲解Async/Await的工作原理、语法特性和最佳实践。 ## 基本概念 Async/Await提供了一种更直观的方式来处理异步操作,使异步代码看起来像同步代码。 ```javascript // 基本语法示例 async function fetchUserData() { try { const response = await fetch('https://api.example.com/user'); const data = await response.json(); return data; } catch (error) { console.error('Error:', error); throw error; } } ``` ## 工作原理 ### 1. Async函数 ```javascript class AsyncFunction { static async example() { // async函数总是返回Promise return 'Hello'; } static async throwError() { throw new Error('Something went wrong'); } } // 等价的Promise写法 class PromiseEquivalent { static example() { return Promise.resolve('Hello'); } static throwError() { return Promise.reject(new Error('Something went wrong')); } } ``` ### 2. Await表达式 ```javascript class AwaitMechanism { static async demonstration() { // await会暂停函数执行 const result1 = await Promise.resolve(1); console.log(result1); // 1 // await可以等待任何thenable对象 const result2 = await { then(resolve) { setTimeout(() => resolve(2), 1000); } }; console.log(result2); // 2 // await也可以等待普通值 const result3 = await 3; console.log(result3); // 3 } } ``` ## 异步迭代 ### 1. 异步迭代器 ```javascript class AsyncIterator { static async *generateNumbers() { for (let i = 0; i < 3; i++) { await new Promise(resolve => setTimeout(resolve, 1000)); yield i; } } static async consumeNumbers() { for await (const num of this.generateNumbers()) { console.log(num); } } } ``` ### 2. 并行执行 ```javascript class ParallelExecution { static async fetchAll(urls) { // 并行发起所有请求 const promises = urls.map(url => fetch(url)); // 等待所有请求完成 const responses = await Promise.all(promises); // 并行解析JSON return await Promise.all( responses.map(response => response.json()) ); } static async *batchProcess(items, batchSize = 3) { for (let i = 0; i < items.length; i += batchSize) { const batch = items.slice(i, i + batchSize); // 并行处理每个批次 const results = await Promise.all( batch.map(item => this.processItem(item)) ); yield* results; } } } ``` ## 错误处理 ### 1. 基本错误处理 ```javascript class ErrorHandling { static async handleErrors() { try { const result = await this.riskyOperation(); return result; } catch (error) { console.error('Error:', error); // 优雅降级 return this.fallbackOperation(); } finally { // 清理工作 await this.cleanup(); } } static async retryOperation(operation, maxAttempts = 3) { for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await operation(); } catch (error) { if (attempt === maxAttempts) throw error; // 指数退避 await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000) ); } } } } ``` ### 2. 错误边界 ```javascript class ErrorBoundary { static async withBoundary(operation) { try { const result = await operation(); return { success: true, data: result, error: null }; } catch (error) { return { success: false, data: null, error }; } } static async handleMultipleOperations(operations) { const results = []; for (const operation of operations) { results.push(await this.withBoundary(operation)); } return results; } } ``` ## 性能优化 ### 1. 并发控制 ```javascript class ConcurrencyControl { constructor(maxConcurrent = 3) { this.maxConcurrent = maxConcurrent; this.running = 0; this.queue = []; } async add(task) { if (this.running >= this.maxConcurrent) { // 等待槽位 await new Promise(resolve => this.queue.push(resolve)); } this.running++; try { return await task(); } finally { this.running--; if (this.queue.length > 0) { // 释放槽位 this.queue.shift()(); } } } async processAll(tasks) { return Promise.all(tasks.map(task => this.add(task))); } } ``` ### 2. 资源池 ```javascript class ResourcePool { constructor(factory, size = 5) { this.resources = Array(size).fill(null).map(() => factory()); this.busy = new Set(); } async acquire() { while (true) { const resource = this.resources.find(r => !this.busy.has(r)); if (resource) { this.busy.add(resource); return resource; } // 等待资源释放 await new Promise(resolve => setTimeout(resolve, 100) ); } } release(resource) { this.busy.delete(resource); } async use(operation) { const resource = await this.acquire(); try { return await operation(resource); } finally { this.release(resource); } } } ``` ## 最佳实践 ### 1. 函数组合 ```javascript class AsyncComposition { static async pipe(...fns) { return async (input) => { let result = input; for (const fn of fns) { result = await fn(result); } return result; }; } static async waterfall(tasks) { return tasks.reduce(async (promise, task) => { const accumulator = await promise; const result = await task(accumulator); return [...accumulator, result]; }, Promise.resolve([])); } } ``` ### 2. 缓存优化 ```javascript class AsyncCache { constructor() { this.cache = new Map(); this.pending = new Map(); } async get(key, factory) { // 检查缓存 if (this.cache.has(key)) { return this.cache.get(key); } // 检查是否有pending请求 if (this.pending.has(key)) { return this.pending.get(key); } // 创建新请求 const promise = factory() .then(result => { this.cache.set(key, result); this.pending.delete(key); return result; }) .catch(error => { this.pending.delete(key); throw error; }); this.pending.set(key, promise); return promise; } invalidate(key) { this.cache.delete(key); this.pending.delete(key); } } ``` ## 调试技巧 ### 1. 异步堆栈跟踪 ```javascript class AsyncDebug { static async traceCalls() { console.log('Entering function'); try { await this.nestedCall(); } catch (error) { console.log('Stack:', error.stack); } } static async nestedCall() { await new Promise(resolve => setTimeout(resolve, 100)); throw new Error('Debug stack trace'); } } ``` ### 2. 性能监控 ```javascript class AsyncMonitor { static async measureTime(operation) { const start = performance.now(); try { return await operation(); } finally { const duration = performance.now() - start; console.log(`Operation took ${duration}ms`); } } static async profile(operation) { console.profile('Async Operation'); try { return await operation(); } finally { console.profileEnd(); } } } ``` ## 总结 Async/Await是JavaScript中处理异步操作的强大特性,它提供了: 1. 更清晰的异步代码结构 2. 简化的错误处理机制 3. 更好的调试体验 4. 灵活的并发控制 在实际开发中,我们应该: 1. 理解Async/Await的工作原理 2. 合理处理错误情况 3. 注意性能优化 4. 遵循最佳实践 5. 善用调试工具