1. 程式人生 > 其它 >手寫Promise結構的設計和then方法

手寫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都會執行,鏈式呼叫等等