手写Promise结构的设计和then方法
1:结构的设计
主要思路:
构造函数 Class----就可以new来调用
利用constructor实现函数的调用(executor)
实现调用了reject()resolve无效调用 ---记录Promise的状态
const PEOMISE_STATUS_PENDING='pending' 默认状态
const PEOMISE_STATUS_FULFILLED='fulfilled'
const PEOMISE_STATUS_REJECTED='rejected'
if判断是某状态就执行某回调
考虑传递参数 保存参数默认undefined
2:then方法
在构造的类里面写一个then函数
执行then传入进来的回调函数
巧妙运用定时器来调整代码执行顺序----->queueMicrotask(规范)
1 const PEOMISE_STATUS_PENDING = 'pending' 2 const PEOMISE_STATUS_FULFILLED = 'fulfilled' 3 const PEOMISE_STATUS_REJECTED = 'rejected' 4 class tyyPromise { 5 constructor(executor) { 6 this.status = PEOMISE_STATUS_PENDING 7 this.value = undefined 8 this.reason = undefined 9 const resolve = (value) => { 10 if (this.status === PEOMISE_STATUS_PENDING) { 11 this.status = PEOMISE_STATUS_FULFILLED 12 queueMicrotask(() => { 13 this.value = value 14 this.onFulfilled(this.value); 15 }) 16 } 17 18 19 } 20 const reject = (reason) => { 21 if (this.status === PEOMISE_STATUS_PENDING) { 22 this.status = PEOMISE_STATUS_REJECTED 23 //以免then还没执行 24 queueMicrotask(() => { 25 this.reason = reason 26 this.onFulfilled(this.reason); 27 }) 28 } 29 } 30 31 executor(resolve, reject) 32 } 33 then(onFulfilled, onRejected) { 34 this.onFulfilled = onFulfilled 35 this.onRejected = onRejected 36 37 } 38 } 39 const promise = new tyyPromise((resolve, reject) => { 40 // console.log('pending'); 41 reject(111) 42 resolve(222) 43 44 }) 45 promise.then(res => { 46 console.log('res:', res); 47 }, err => { 48 console.log('err:', err); 49 })

这样就能简单的实现Promise的基本功能
但是有待完善 比如 多次调用then都会执行,链式调用等等

浙公网安备 33010602011771号