最近2018中文字幕在日韩欧美国产成人片_国产日韩精品一区二区在线_在线观看成年美女黄网色视频_国产精品一区三区五区_国产精彩刺激乱对白_看黄色黄大色黄片免费_人人超碰自拍cao_国产高清av在线_亚洲精品电影av_日韩美女尤物视频网站

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
es6-promise源碼的示例分析

這篇文章給大家分享的是有關(guān)es6-promise源碼的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)建站2013年開創(chuàng)至今,先為薩迦等服務(wù)建站,薩迦等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為薩迦企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

主要邏輯:

本質(zhì)上還是回調(diào)函數(shù)那一套。
通過_subscribers的判斷完成異步和同步的區(qū)分。
通過 resolve,reject -> publish -> invokeCallback -> resolve,reject的遞歸和下一條then的parent是上一條的child來完成then鏈的流轉(zhuǎn)

同步情況下函數(shù)流轉(zhuǎn): constructor -> resolver -> publish -> then -> invokeCallback
異步情況下函數(shù)流轉(zhuǎn): constructor -> then -> resolver -> publish -> invokeCallback

主要函數(shù)解析

1、constructor
作用: 把resolve,reject綁定到 resolver上-

constructor(resolver) {
    this[PROMISE_ID] = nextId();
    this._result = this._state = undefined;
    this._subscribers = [];
    
    if (noop !== resolver) {
      typeof resolver !== 'function' && needsResolver();
      
      this instanceof Promise ? initializePromise(this, resolver) : needsNew();
    }
  }

2 then
作用: 把回調(diào)函數(shù)綁定在_subscribers上,catch和finally本質(zhì)是then的語法糖
 _subscribers的參數(shù)是一個數(shù)組,[0]是他的child,綁定下一個then鏈的parent,用于publish遞歸調(diào)用, 第二個是resolve 回調(diào), 第三個是reject回調(diào)

export default function then(onFulfillment, onRejection) {
  const parent = this;
  
  const child = new this.constructor(noop);

  if (child[PROMISE_ID] === undefined) {
    makePromise(child);
  }

  const { _state } = parent;
 
  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的觸發(fā)會調(diào)用publish,publish繼續(xù)調(diào)用invokeCallback,通過返回值繼續(xù)調(diào)用resolve,reject,形成一個遞歸,完成then鏈的流轉(zhuǎn)

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是沒有返回參數(shù)的,基于

return promise.then(value => constructor.resolve(callback()).then(() => value),
                         reason => constructor.resolve(callback()).then(() => { throw reason; }));

感謝各位的閱讀!關(guān)于es6-promise源碼的示例分析就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!


文章題目:es6-promise源碼的示例分析
地址分享:http://fisionsoft.com.cn/article/jpgdhg.html