promise源碼解析


前言

大部分同學對promise,可能還停留在會使用es6的promise,還沒有深入學習。我們都知道promise內部通過reslove、reject來判斷執行哪個函數,原型上面的then同樣的,也有成功回調函數跟失敗回調函數。

這篇文章,我們來講講promise的源碼,從源碼來分析,promise的原理。Tip:  閱讀源碼是枯燥的

 

使用

使用es6的promise常用的方式有兩種:
1、使用CDN 引入方式,我們在html中引入es6-promise.js
es6-promise.auto.js這兩個js文件,就可以使用了。
2、通過node安裝方式,有兩種安裝方式:
yarn add es6-promise
or
npm install es6-promise

安裝完成后就可以使用了,比如:var Promise = require('es6-promise').Promise;

Tip:
如果要在Node或瀏覽器中通過CommonJS填充全局環境,請使用以下代碼段:
require('es6-promise').polyfill();
require('es6-promise/auto');
這里不會將結果分配polyfill ()給任何變量。該polyfill ()方法將Promise在調用時修補全局環境。


分析
聲明Promise
var Promise$1 = function () {
  function Promise(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();
    }
  }

從代碼上可以看出跟promise交互的主要方式是通過其`then`方法,它會記錄回調用來接收promise的最終值或者promise無法履行的原因。

我們來看看resolve方法:

function resolve$1(object) {
  /*jshint validthis:true */
  var Constructor = this;

  if (object && typeof object === 'object' && object.constructor === Constructor) {
    return object;
  }

  var promise = new Constructor(noop);
  resolve(promise, object);
  return promise;
}
function resolve(promise, value) {
  // 首先一個Promise的resolce結果不能是自己 (自己返回自己然后等待自己,循環)
  if (promise === value) {
    reject(promise, selfFulfillment());
  } else if (objectOrFunction(value)) {
    // 當新的值存在,類型是對象或者函數的時候
    handleMaybeThenable(promise, value, getThen(value));
  } else {
    // 最終的結束流程,都是進入這個函數
    fulfill(promise, value);
  }
}

`Promise.resolve`會返回一個將被resolve的promise傳遞了“value”。 我們可以用下面的簡寫:

  let promise = Promise.resolve(1);
  promise.then(function(value){
    // value === 1
  });

最后看下then方法:

Promise.prototype.then = function (didFulfill, didReject) {
    if (debug.warnings() && arguments.length > 0 &&
        typeof didFulfill !== "function" &&
        typeof didReject !== "function") {
        var msg = ".then() only accepts functions but was passed: " +
                util.classString(didFulfill);
        if (arguments.length > 1) {
            msg += ", " + util.classString(didReject);
        }
        this._warn(msg);
    }
    return this._then(didFulfill, didReject, undefined, undefined, undefined);
};

 

總結:
promise執行步驟如下:
1、 首先創建Promise 2、 然后設置需要執行的函數 3、 接着設置完成的回調 4、 跟着開始執行函數 5、 最后根據執行結果選擇回調



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM