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

手写ES6 Promise() 相关函数

手写 Promise() 相关函数:

Promise()、then()、catch()、finally()

// 定义三种状态常量
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'class MyPromise {/*定义状态和结果两个私有属性:1.使用 # 语法(ES2022+ 官方私有字段):在类中通过 # 前缀声明属性,该属性仅在类的内部可访问2.Symbol 作为属性键:用 Symbol 作为属性名,外部无法直接获取 Symbol 引用。*/#state = PENDING // 状态#result = undefined // 结果#thenables = [] // 存储 then 方法回调的队列constructor(executor) {// resolve 和 reject 主要功能即为改变状态,设置结果const resolve = (value) => { // 解决时调用this.#changeState(FULFILLED, value)}const reject = (reason) => { // 拒绝时调用this.#changeState(REJECTED, reason)}try { // 只能捕获同步错误,无法捕获异步错误,如 setTimeout 里的错误executor(resolve, reject)} catch (err) {reject(err)}}// 改变状态和设置结果的私有方法#changeState(state, result) {if (this.#state !== PENDING) returnthis.#state = statethis.#result = resultthis.#run()}// 处理 then 回调的私有方法#handleCallback(callback, resolve, reject) {if (typeof callback !== 'function') { // 状态穿透,即 then 方法返回的 Promise 状态与当前 Promise 状态保持一致// then 回调是微任务,需要放到微任务队列中执行queueMicrotask(() => { // 参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/queueMicrotaskconst settled = this.#state === FULFILLED ? resolve : rejectsettled(this.#result)})return}queueMicrotask(() => {try {const result = callback(this.#result)// 如果返回值是一个 Promise,则等待它完成后再 resolveif (result instanceof MyPromise) {result.then(resolve, reject)} else {resolve(result)}} catch (err) {reject(err)}})}/*执行队列的私有方法,两个执行时机:1.Promise 状态改变时2.then 方法被调用时*/#run() {if (this.#state === PENDING) return// 取出队列中的回调函数,依次执行(先进先出原则)while (this.#thenables.length) {const { onFulfilled, onRejected, resolve, reject } = this.#thenables.shift()try {if (this.#state === FULFILLED) { // 执行 onFulfilled 回调函数this.#handleCallback(onFulfilled, resolve, reject)} else { // 执行 onRejected 回调函数this.#handleCallback(onRejected, resolve, reject)}} catch (err) {reject(err)}}}/*onFulfilled 可选:一个在此 Promise 对象被兑现时异步执行的函数。它的返回值将成为 then() 返回的 Promise 对象的兑现值。onRejected 可选:一个在此 Promise 对象被拒绝时异步执行的函数。它的返回值将成为 catch() 返回的 Promise 对象的兑现值。*/then(onFulfilled, onRejected) {return new MyPromise((resolve, reject) => {// 将四个回调函数放入队列,以便立即或将来处理this.#thenables.push({onFulfilled,onRejected,resolve,reject})// 启动队列处理this.#run()})}catch(onRejected) {return this.then(undefined, onRejected)}finally(onFinally) {this.then((value) => {MyPromise.resolve(onFinally()).then(() => value)},(reason) => {MyPromise.resolve(onFinally()).then(() => { throw reason })})}
}

验证测试 MyPromise() 函数

const p1 = new Promise((resolve, reject) => {resolve(1)reject(2)
})
console.log('p1', p1)
const p2 = new Promise(() => { throw 123 })
console.log('p2', p2)
const p3 = new Promise((resolve, reject) => {setTimeout(() => {resolve('setTimeout') // 无法捕获}, 0)
})
console.log('p3', p3)
const myP1 = new MyPromise((resolve, reject) => {resolve(1)reject(2)
})
console.log('myP1', myP1)
myP1.then((res) => {console.log('res', res) // 1return res + 1},(err) => {console.log('err', err) // 1}
).then((res) => {console.log('res', res) // 2// throw 'error'return res + 1
}).then((res) => {console.log('res', res) // 3
}).catch((err) => {console.log('err', err)
}).finally(() => {console.log('finally')
})
const myP2 = new MyPromise(() => { throw 123 })
console.log('myP2', myP2)
const myP3 = new MyPromise((resolve, reject) => {setTimeout(() => {resolve('setTimeout') // 无法捕获}, 0)
})
console.log('myP3', myP3)
http://www.xdnf.cn/news/595657.html

相关文章:

  • 怎么把https://github.com项目拉到自己的github
  • 在Ubuntu18.04下搭建SadTalker让图片开口说话
  • 第五章:异步幻境 · 时间与数据的秘密
  • STM32之温湿度传感器(DHT11)
  • 纯惯导(INS)的误差来源及其对静态漂移曲线的影响
  • SS928V100(Hi3403V100)----NNN推理引擎,AMCT-ONNX模型压缩量化踩坑记录(LINUX版)
  • 数据指标体系:企业数字化转型的“数字基因“革命
  • Even Split_CodeForces - 1666E分析与解答
  • 【三轴加速度计】QMA6100P数据手册解析
  • 基于RFSOC49DR-16收16发 PCIE4.0 X8 射频采集卡
  • 航电系统之云台检测技术篇
  • 5月22总结
  • 浅聊一下搭建企业私有知识库的可行方案
  • Springboot3
  • mapbox V3 新特性,实现三维等高线炫酷效果
  • Linux(Ubuntu)新建文件权限继承问题
  • MQTT-主题(Topic)
  • DeepSeek:以开源之力,引领AI技术新风潮
  • MySQL初阶:JDBC
  • 海盗王客户端创建角色遮罩层修改成自适应窗口尺寸
  • 学习笔记:黑马程序员JavaWeb开发教程(2025.4.10)
  • QT入门基础
  • python训练营打卡第31天
  • 【C++】控制台小游戏
  • 【人工智能】低代码基础技术讲解,规则引擎,在低代码平台上的作用,有哪些规则引
  • 前端请求状态出现CORS错误
  • CarPlay有线连接流程
  • 陕西安全员考试报名流程是怎样的?
  • 【Python3教程】Python3 文件(File)方法详解
  • 谷歌开源医疗领域多模态生成式AI模型:medgemma-4b-it