元素码农
基础
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:38
↑
☰
# JavaScript Promise实现原理 Promise是JavaScript中处理异步操作的核心机制。本文将深入讲解Promise的实现原理、状态管理和异步处理流程。 ## Promise基本概念 Promise是一个代表异步操作最终完成或失败的对象。它有三种状态: 1. pending(进行中) 2. fulfilled(已成功) 3. rejected(已失败) ```javascript // Promise状态示例 class PromiseState { static PENDING = 'pending'; static FULFILLED = 'fulfilled'; static REJECTED = 'rejected'; } // Promise基本用法 const promise = new Promise((resolve, reject) => { // 异步操作 setTimeout(() => { const random = Math.random(); if (random > 0.5) { resolve('Success'); } else { reject('Failed'); } }, 1000); }); promise .then(result => console.log('Success:', result)) .catch(error => console.log('Error:', error)); ``` ## Promise实现机制 ### 1. 基本结构 ```javascript class MyPromise { constructor(executor) { this.state = PromiseState.PENDING; this.value = undefined; this.reason = undefined; this.onFulfilledCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.state === PromiseState.PENDING) { this.state = PromiseState.FULFILLED; this.value = value; this.onFulfilledCallbacks.forEach(fn => fn()); } }; const reject = (reason) => { if (this.state === PromiseState.PENDING) { this.state = PromiseState.REJECTED; this.reason = reason; this.onRejectedCallbacks.forEach(fn => fn()); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { // 实现链式调用 return new MyPromise((resolve, reject) => { if (this.state === PromiseState.FULFILLED) { try { const result = onFulfilled(this.value); resolve(result); } catch (error) { reject(error); } } else if (this.state === PromiseState.REJECTED) { try { const result = onRejected(this.reason); resolve(result); } catch (error) { reject(error); } } else { this.onFulfilledCallbacks.push(() => { try { const result = onFulfilled(this.value); resolve(result); } catch (error) { reject(error); } }); this.onRejectedCallbacks.push(() => { try { const result = onRejected(this.reason); resolve(result); } catch (error) { reject(error); } }); } }); } catch(onRejected) { return this.then(null, onRejected); } } ``` ### 2. 静态方法实现 ```javascript class MyPromise { static resolve(value) { return new MyPromise(resolve => resolve(value)); } static reject(reason) { return new MyPromise((resolve, reject) => reject(reason)); } static all(promises) { return new MyPromise((resolve, reject) => { const results = []; let completed = 0; promises.forEach((promise, index) => { promise.then(result => { results[index] = result; completed++; if (completed === promises.length) { resolve(results); } }).catch(reject); }); }); } static race(promises) { return new MyPromise((resolve, reject) => { promises.forEach(promise => { promise.then(resolve).catch(reject); }); }); } static allSettled(promises) { return new MyPromise(resolve => { const results = []; let completed = 0; promises.forEach((promise, index) => { promise .then(value => { results[index] = { status: 'fulfilled', value }; }) .catch(reason => { results[index] = { status: 'rejected', reason }; }) .finally(() => { completed++; if (completed === promises.length) { resolve(results); } }); }); }); } } ``` ## Promise链式调用 ### 1. 基本链式调用 ```javascript class PromiseChain { static example() { return new Promise(resolve => resolve(1)) .then(value => { console.log(value); // 1 return value + 1; }) .then(value => { console.log(value); // 2 return Promise.resolve(value + 1); }) .then(value => { console.log(value); // 3 throw new Error('Something went wrong'); }) .catch(error => { console.error(error); return 'Recovered'; }) .then(value => { console.log(value); // 'Recovered' }); } } ``` ### 2. 异步链式调用 ```javascript class AsyncChain { static async fetchUserData(userId) { try { const user = await this.fetchUser(userId); const posts = await this.fetchPosts(user.id); const comments = await this.fetchComments(posts[0].id); return { user, posts, comments }; } catch (error) { console.error('Error fetching data:', error); throw error; } } static fetchUser(userId) { return new Promise(resolve => { setTimeout(() => { resolve({ id: userId, name: 'John' }); }, 1000); }); } static fetchPosts(userId) { return new Promise(resolve => { setTimeout(() => { resolve([{ id: 1, userId, title: 'Post 1' }]); }, 1000); }); } static fetchComments(postId) { return new Promise(resolve => { setTimeout(() => { resolve([{ id: 1, postId, text: 'Comment 1' }]); }, 1000); }); } } ``` ## Promise错误处理 ### 1. 错误传播 ```javascript class ErrorHandling { static demonstrateErrorPropagation() { return Promise.resolve(1) .then(value => { throw new Error('Error in first then'); }) .then( value => console.log('This will be skipped'), error => { console.error('Caught in second then:', error); throw error; // 继续传播错误 } ) .catch(error => { console.error('Caught in catch:', error); return 'Recovered'; }) .then(value => { console.log('Final value:', value); }); } } ``` ### 2. 异步错误处理 ```javascript class AsyncErrorHandling { static async handleAsyncErrors() { try { const result = await this.riskyOperation(); console.log('Success:', result); } catch (error) { console.error('Error:', error); // 优雅降级 return this.fallbackOperation(); } finally { // 清理工作 this.cleanup(); } } static async riskyOperation() { throw new Error('Operation failed'); } static async fallbackOperation() { return 'Fallback result'; } static cleanup() { console.log('Cleaning up...'); } } ``` ## Promise性能优化 ### 1. 并发控制 ```javascript class PromisePool { constructor(maxConcurrent) { this.maxConcurrent = maxConcurrent; this.running = 0; this.queue = []; } async add(promiseFactory) { if (this.running >= this.maxConcurrent) { // 等待某个任务完成 await new Promise(resolve => this.queue.push(resolve)); } this.running++; try { return await promiseFactory(); } finally { this.running--; if (this.queue.length > 0) { // 通知下一个任务开始 this.queue.shift()(); } } } async addAll(promiseFactories) { return Promise.all( promiseFactories.map(factory => this.add(factory)) ); } } ``` ### 2. 缓存优化 ```javascript class PromiseCache { constructor() { this.cache = new Map(); } async get(key, promiseFactory) { if (!this.cache.has(key)) { // 缓存Promise而不是结果 this.cache.set(key, promiseFactory()); } try { return await this.cache.get(key); } catch (error) { // 如果失败则删除缓存 this.cache.delete(key); throw error; } } invalidate(key) { this.cache.delete(key); } clear() { this.cache.clear(); } } ``` ## 最佳实践 ### 1. Promise包装 ```javascript class PromiseWrapper { static promisify(fn) { return function (...args) { return new Promise((resolve, reject) => { fn.call(this, ...args, (error, result) => { if (error) reject(error); else resolve(result); }); }); }; } static delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } static timeout(promise, ms) { const timeoutPromise = this.delay(ms) .then(() => { throw new Error('Operation timed out'); }); return Promise.race([promise, timeoutPromise]); } } ``` ### 2. 错误处理最佳实践 ```javascript class PromiseErrorHandler { static async retryWithBackoff(operation, maxAttempts = 3) { for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await operation(); } catch (error) { if (attempt === maxAttempts) throw error; // 指数退避 const delay = Math.pow(2, attempt) * 1000; await PromiseWrapper.delay(delay); } } } static createErrorBoundary(promise) { return promise .then(data => ({ data, error: null })) .catch(error => ({ data: null, error })); } } ``` ## 总结 Promise是JavaScript异步编程的核心机制,它提供了: 1. 可靠的状态管理 2. 优雅的错误处理 3. 灵活的链式调用 4. 强大的并发控制 在实际开发中,我们应该: 1. 理解Promise的状态转换机制 2. 正确处理异步错误 3. 合理控制并发 4. 优化Promise性能 5. 遵循最佳实践