第一步:Promise構造函數接受一個函數作為參數,該函數的兩個參數分別是:resolve和reject;
function Promise(task) { // 緩存this let that = this // 進行中的狀態 this.status = 'pending' //初始值 this.value = undefined // 存放成功后要執行的回調函數的序列 that.onResolvedCallbacks = [] // 存放失敗后要執行的回調函數的序列 that.onRejectCallbacks = [] // 該方法將Promise由pending變為fulfiled function resolve(value) { if(that.status == 'pending') { that.status = 'fulfiled' that.value = value that.onResolvedCallbacks.forEach(cb => cb(that.value)) } } // 該方法是將Promise由pending變成rejected function reject(reason) { if(that.status == 'pending') { that.status = 'rejected' that.value = reason that.onRejectCallbacks.forEach(cb => cb(that.value)) } } try { // 每一個Promise在new一個實例的時候 接受的函數都是立即執行的 task(resolve, reject) } catch(e) { reject(e) } }
第二部 寫then方法,接收兩個函數onFulfilled onRejected,狀態是成功態的時候調用onFulfilled 傳入成功后的值,失敗態的時候執行onRejected,傳入失敗的原因,pending 狀態時將成功和失敗后的這兩個方法緩存到對應的數組中,當成功或失敗后 依次再執行調用
Promise.prototype.then = function(onFulfilled, onRejected) { if(this.status == 'fulfiled') { onFulfilled(this.value) } if(this.status == 'rejected') { onRejected(this.value) } if (this.status == 'pending') { this.onResolvedCallbacks.push(onFulfilled(this.value)); this.onRejectCallbacks.push(onRejected(this.value)); } } new Promise(function (resolve, reject) { resolve(100);// reject(100) }).then(function (data) { console.log('666', data) })