極簡版Promise 知足的使用方式git
new MyPromise()
MyPromise.resolve()
,目前靜態方法僅支持resolve
& reject
親測使用OK,歡迎指教,互相學習,github連接,歡迎star。
附贈利用構造函數手寫Promise 的方法,github連接。github
class MyPromise { constructor(fn) { // 定義Promise 三種狀態 this.states = { PENDING: 'PENDING', RESOLVED: 'RESOLVED', REJECTED: 'REJECTED' } // 定義傳遞到then的value this.value = null // 定義當前Promise運行狀態 this.state = this.states.PENDING // 定義Promise失敗狀態的回調函數集合 this.resolvedCallBacks = [] // 定義Promise成功狀態的回調函數集合 this.rejectedCallBacks = [] // 爲靜態方法定義其內部使用的指向實例的that MyPromise.that = this try { // 執行 new MyPromise() 內傳入的方法 fn(MyPromise.resolve, MyPromise.reject) } catch (error) { MyPromise.reject(this.value) } } // 靜態resolve方法,MyPromise實例不可訪問; //支持類MyPromise訪問,例:MyPromise.resolve('success').then(e=>e) static resolve(value) { // 因爲靜態方法內部的this指向 類 而不是 實例,因此用下面的方法訪問實例對象 const that = MyPromise.that // 判斷是不是MyPromise實例訪問resolve const f = that instanceof MyPromise // MyPromise實例對象訪問resolve if (f && that.state == that.states.PENDING) { that.state = that.states.RESOLVED that.value = value that.resolvedCallBacks.map(cb => (that.value = cb(that.value))) } // MyPromise類訪問resolve if (!f) { const obj = new MyPromise() return Object.assign(obj, { state: obj.states.RESOLVED, value }) } } // 靜態reject方法,MyPromise實例不可訪問; //支持類MyPromise訪問,例:MyPromise.reject('fail').then(e=>e) static reject(value) { const that = MyPromise.that const f = that instanceof MyPromise if (f && that.state == that.states.PENDING) { that.state = that.states.REJECTED that.value = value that.rejectedCallBacks.map(cb => (that.value = cb(that.value))) } if (!f) { const obj = new MyPromise() return Object.assign(obj, { state: obj.states.REJECTED, value }) } } // 定義在MyPromise原型上的then方法 then(onFulfilled, onRejected) { const { PENDING, RESOLVED, REJECTED } = this.states const f = typeof onFulfilled == "function" ? onFulfilled : c => c; const r = typeof onRejected == "function" ? onRejected : c => { throw c; }; switch (this.state) { case PENDING: // ‘PENDING’狀態下向回調函數集合添加callback this.resolvedCallBacks.push(f) this.rejectedCallBacks.push(r) break; case RESOLVED: // 將回調函數的返回值賦值給 實例的 value,知足鏈式調用then方法時傳遞value this.value = f(this.value) break; case REJECTED: // 同上 this.value = r(this.value) break; default: break; } // 知足鏈式調用then,返回MyPromise實例對象 return this } } MyPromise.resolve('success').then((e) => { console.log(e); return e + 1 }).then( res=> { console.log(res); }) new MyPromise(resolve => { setTimeout(() => { resolve(1); }, 2000); }) .then(res1 => { console.log(res1); return 2; }) .then(res2 => console.log(res2 ));