這篇文章帶給大家的內容是關於es6-promise源碼的分析,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
主要邏輯:
本質上還是回呼函數那一套。
透過_subscribers的判斷完成非同步和同步的區分。
透過resolve,reject -> publish -> invokeCallback -> resolve,reject的遞歸和下一條then的parent是上一條的child來完成then鏈的流轉
同步情況下函數流轉: constructor -> resolver -> publish -> then -> invokeCallback
非同步情況下函數流轉: constructor -> then -> resolver -> publish -> invokeCallback
作用: 把resolve,reject綁定到resolver上-
constructor(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; <!-- 判断resolver是不是一个空对象 --> if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); <!-- 把resolve,reject绑定到 resolver上--> this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } }
2 then 作用:把回調函數綁定在_subscribers上,catch和finally本質是then的語法糖
_subscribers的參數是一個數組,[0]是他的child,綁定下一個then鏈的parent,用於publish遞歸調用,第二個是resolve 回調, 第三個是reject回呼
export default function then(onFulfillment, onRejection) { const parent = this; <!-- 用于then链的返回值,下一条then就是当前parent的child --> const child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } const { _state } = parent; <!-- 判断_state的状态,是不是PENDING --> if (_state) { const callback = arguments[_state - 1]; asap(() => invokeCallback(_state, child, callback, parent._result)); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; }
3 publish 作用:resolve,reject的觸發會呼叫publish,publish繼續呼叫invokeCallback,透過回傳值繼續呼叫resolve,reject,形成一個遞歸,完成then鏈的流轉
function publish(promise) { let subscribers = promise._subscribers; let settled = promise._state; if (subscribers.length === 0) { return; } let child, callback, detail = promise._result; for (let i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; }
tip: finally的callback是沒有回傳參數的,基於
return promise.then(value => constructor.resolve(callback()).then(() => value), reason => constructor.resolve(callback()).then(() => { throw reason; }));
JavaScript影片教學欄位!
以上是es6-promise源碼的分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!