簡(jiǎn)單實(shí)現(xiàn)Promise

前幾天看一本書(shū),叫做《Neural Network and Deep Learning》. 這本書(shū)中介紹了神經(jīng)網(wǎng)絡(luò)一些很神奇的概念,最特色的是,難得有人去思考和追究這一切看上去似乎很好的概念最開(kāi)始是怎么來(lái)的,為什么我們會(huì)想到這種東西?

每當(dāng)我看到j(luò)avascript中的Promise也是這么想,這種設(shè)計(jì)?難道是天上掉下來(lái)的,最初的人們到底是怎么想到這種規(guī)范的呢?然而大多數(shù)人并不討論這些東西,我們不用知道歷史和原理,就能自由使用Promise。就像神經(jīng)網(wǎng)絡(luò)中,你不用知道為什么人們會(huì)發(fā)現(xiàn)L1 and L2 regularization,也不用想sigmoid函數(shù)為什么會(huì)被選中,按照推出的公式就能很好的使用它。

但對(duì)某些人來(lái)說(shuō),我們還是好奇,它為啥會(huì)出現(xiàn),它怎么實(shí)現(xiàn)的?

我只是自己做著玩,讀者不用太認(rèn)真。如果有指教,歡迎ping me。

歷史

Javascript中Promise的來(lái)源

實(shí)現(xiàn)

首先,你得知道閉包是什么。

我們先看看,需要新建一個(gè)Promise對(duì)象,這個(gè)對(duì)象構(gòu)建時(shí)接受一個(gè)函數(shù)。

這個(gè)函數(shù)中是一個(gè)異步操作,即在5秒之后,才會(huì)返回

function Promise(fn) {
  console.log("[In Promise] start");
  this.__name__ = "My promise";
  var cbs = [];
  function resolve(value) {
    console.log("[In Promise.resolve] start");
    cbs.forEach(function(cb){
      cb(value);
    });
    console.log("[In Promise.resolve] finish");
  }

  this.then = function(callback) {
    cbs.push(callback);
  }

  fn(resolve);
  console.log("[In Promise] finished");
  console.log("# about 5 seconds later...")
}

var p1 = new Promise(function(resolve, reject){
  console.log("[In executor function] start");
  setTimeout(function(){
    resolve(12);
  }, 5000);
  console.log("[In executor function] finish");
})
p1.then(function(v){console.log(v)});
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-15 10:45:55]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
# about 5 seconds later...
[In Promise.resolve] start
12
[In Promise.resolve] finish

我們看到,new這個(gè)Promise的時(shí)候,給了它一個(gè)函數(shù)作為參數(shù),這個(gè)函數(shù)叫做executor函數(shù),接受兩個(gè)參數(shù),分別對(duì)應(yīng)Promise函數(shù)里定義的resolve和reject。一種約定。

我們?cè)谶@個(gè)executor里異步調(diào)用resolve函數(shù),直到某個(gè)時(shí)刻之后,才給他一個(gè)值12. 一個(gè)典型的異步操作。

通過(guò)以上機(jī)制,我們構(gòu)建了一個(gè)Promise對(duì)象,這個(gè)Promise能處理我們?cè)趀xecutor函數(shù)中未來(lái)某個(gè)時(shí)刻的異步返回,返回值之后交給我們通過(guò)then綁定到Promise中的函數(shù)(cbs)來(lái)處理(由Promise類(lèi)中定義的resolve實(shí)現(xiàn))。

但是,如果executor是同步代碼

var p2 = new Promise(function(resolve){
  resolve(12);
})
p2.then(function(v){console.log(v)});
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-15 10:49:45]
└─[1] <> node promise.js
[In Promise] start
[In Promise.resolve] start
[In Promise.resolve] finish
[In Promise] finished

沒(méi)反應(yīng)了就。。。因?yàn)?,cb沒(méi)東西的時(shí)候程序就運(yùn)行完了。。。

所以,重新實(shí)現(xiàn) Promise類(lèi)中的resolve函數(shù),用setTimeout將Promise.resolve強(qiáng)行置于同步代碼(then)之后。

function resolve(value) {
    console.log("[In Promise.resolve] start");
    setTimeout(function() {
      cbs.forEach(function(cb){
        cb(value);
      });
    }, 0);
    console.log("[In Promise.resolve] finish");
  }
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-15 11:20:01]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In Promise.resolve] start
[In Promise.resolve] finish
[In executor function] finish
[In Promise] finished
12

我覺(jué)得挺好。。。好像沒(méi)有問(wèn)題的樣子

p1.then(function(v){console.log(v + 1)});
p1.then(function(v){console.log(v - 1)});
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-15 11:38:33]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[In Promise.resolve] start
[In Promise.resolve] finish
13
11

然而。。。

p1.then(function(v){console.log(v + 1)});
setTimeout(function() {
   console.log("call then later");
  p1.then(function(v){console.log(v - 1)});
}, 5000);
└─[0] <> node promise.js
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-15 11:41:08]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[In Promise.resolve] start
[In Promise.resolve] finish
13
call then later

消失了?只能調(diào)用一次?當(dāng)你通過(guò)then往cbs里注冊(cè)回調(diào)的時(shí)候,executor里的異步調(diào)用已經(jīng)返回,resolve已經(jīng)執(zhí)行了。

Promise對(duì)象應(yīng)該緩存異步返回的值,讓接下來(lái)的then可以直接調(diào)用。

所以要引入狀態(tài)和緩存

function Promise(fn) {
  console.log("[In Promise] start");
  this.__name__ = "My promise";
  var cbs = []; // 因?yàn)槲蚁雝hen好幾次
  var status = "pending";
  var cache;

  function resolve(value) {
    console.log("[In Promise.resolve] start");
    cache = value;
    status = "fulfilled";
    setTimeout(function() {
      cbs.forEach(function(cb){
        cb(value);
      });
    }, 0);
    console.log("[In Promise.resolve] finish");
  }

  this.then = function(callback) {
    if (status == "pending") {
      console.log("[Register then]status pending!")
      cbs.push(callback);
    } else if (status == "fulfilled") {
      console.log("[Register then]status fulfilled!")
      callback(cache);
    }
  }

  fn(resolve);
  console.log("[In Promise] finished");
}
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-16 12:02:01]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[Register then]status pending!
[In Promise.resolve] start
[In Promise.resolve] finish
13
call then later
[Register then]status fulfilled!
11

這就對(duì)了。接下來(lái),Promise要串行的話。。。

var p3 = new Promise(function(resolve, reject){
  console.log("[In executor function] start");
  setTimeout(function(){
    resolve(12);
  }, 2000);
  console.log("[In executor function] finish");
})
p3.then(function(v){
  console.log(v+1);
 return v+1
})
.then(function(v){
  console.log(v);
});
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-16 11:20:16]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[Register then]status pending!
/home/reverland/tmp/Promise/promise.js:63
.then(function(v){
^

TypeError: Cannot read property 'then' of undefined
    at Object.<anonymous> (/home/reverland/tmp/Promise/promise.js:63:1)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3

顯然,我們的then方法沒(méi)有返回。

為了銜接當(dāng)前Promise和下一個(gè),then函數(shù)返回一個(gè)Bridge Promise,Bridge Promise的executor函數(shù)做了以下事情:

  • 如果當(dāng)前Promise fulfilled的話就調(diào)用then函數(shù)的參數(shù)中的callback,并把當(dāng)前Promise異步返回的值作為參數(shù)傳入。調(diào)用Bridge Promise的resolve讓Bridge Promise進(jìn)入fulfill狀態(tài)。
  • 如果當(dāng)前Promise沒(méi)有fulfilled就在隊(duì)列中添加回調(diào)。

我們重新確認(rèn)下,Promise的原理。對(duì)executor中的異步返回,我們把它傳給Promise的resolve方法。該方法負(fù)責(zé)將用then注冊(cè)的回調(diào)隊(duì)列執(zhí)行(如果不是pending狀態(tài)),并傳入異步返回值作為參數(shù)。

而串聯(lián)的時(shí)候則是,返回新的Promise,該P(yáng)romise的executor中用當(dāng)前Promise注冊(cè)的callback和新Promise的resolve來(lái)實(shí)現(xiàn)將注冊(cè)callback返回的值送給新的Promise的resolve來(lái)完成新的Promise狀態(tài)轉(zhuǎn)變?yōu)閒ulfilled這么一個(gè)過(guò)程。

function Promise(fn) {
  console.log("[In Promise] start");
  this.__name__ = "My promise";
  var dfs = []; 
  var status = "pending";
  var cache;

  function resolve(value) {
    console.log("[In Promise.resolve] start", value);
    cache = value;
    status = "fulfilled";
    setTimeout(function() {
      dfs.forEach(function(df){
        handle(df);
      });
    }, 0);
    console.log("[In Promise.resolve] finish");
  }

  function handle(deferred) {
    if (status == "pending") {
      console.log("[handle] pending")
      dfs.push(deferred);
    } else if (status == "fulfilled") {
      console.log("[handle] fulfilled")
      var ret = deferred.callback(cache);
      deferred.resolve(ret);
    }
  }

  this.then = function(callback) {
    return new Promise(function(resolve, reject) {
      console.log("[New Promise excutor] begin")
      handle({
        callback: callback,
        resolve: resolve
      }); // handle在handle定義的Promise中執(zhí)行如下操作
     // 如果當(dāng)前異步操作完成,將當(dāng)前異步操作的值作為callback參數(shù)調(diào)用,并調(diào)用resolve完成新Promise的異步操作 
      console.log("[New Promise excutor] finished")
    })
  }

  fn(resolve);
  console.log("[In Promise] finished");
}
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-16 12:39:36]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
# 2s later
[In Promise.resolve] start 12
[In Promise.resolve] finish
[handle] fulfilled
13
[In Promise.resolve] start 14
[In Promise.resolve] finish
[handle] fulfilled
14
[In Promise.resolve] start undefined
[In Promise.resolve] finish

看到多了一次Promise的resolve。

然而還是有問(wèn)題,我們想,如果,then綁定的函數(shù)沒(méi)有返回,則默認(rèn)將上次返回值繼續(xù)下傳?,F(xiàn)在卻是直接向下一步返回undefined,如下:

var p3 = new Promise(function(resolve, reject){
  console.log("[In executor function] start");
  setTimeout(function(){
    resolve(12);
  }, 2000);
  console.log("[In executor function] finish");
})
p3.then(function(v){
  console.log(v+1);
})
.then(function(v){
  console.log(v);
});
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-16 12:49:21]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
# 2s later
[In Promise.resolve] start 12
[In Promise.resolve] finish
[handle] fulfilled
13
[In Promise.resolve] start undefined
[In Promise.resolve] finish
[handle] fulfilled
undefined
[In Promise.resolve] start undefined
[In Promise.resolve] finish

稍作修改

  function handle(deferred) {
    if (status == "pending") {
      console.log("[handle] pending")
      dfs.push(deferred);
    } else if (status == "fulfilled") {
      console.log("[handle] fulfilled")
      var ret = deferred.callback(cache);
      if (ret) {
        deferred.resolve(ret);
      } else {
        deferred.resolve(cache);
      }
    }
  }
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-16 12:54:09]
└─[1] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
# about 2s later
[In Promise.resolve] start 12
[In Promise.resolve] finish
[handle] fulfilled
13
[In Promise.resolve] start 12
[In Promise.resolve] finish
[handle] fulfilled
12
[In Promise.resolve] start 12
[In Promise.resolve] finish

看上去非常好!接著是錯(cuò)誤冒泡,跟之前完全類(lèi)似

function Promise(fn) {
  console.log("[In Promise] start");
  this.__name__ = "My promise";
  var dfs = []; 
  var status = "pending";
  var cache;

  function resolve(value) {
    console.log("[In Promise.resolve] start", value);
    cache = value;
    status = "fulfilled";
    finale();
    console.log("[In Promise.resolve] finish");
  }

  function reject(reason) {
    status = 'rejected';
    cache = reason;
    finale();
  }

  function finale() {
    setTimeout(function() {
      dfs.forEach(function(df){
        handle(df);
      });
    }, 0);
  }

  function handle(deferred) {
    if (status == "pending") {
      console.log("[handle] pending")
      dfs.push(deferred);
    } else if (status == "fulfilled") {
      console.log("[handle] fulfilled")
      var ret = deferred.onFulfilled(cache);
      if (ret) {
        deferred.resolve(ret);
      } else {
        deferred.resolve(cache);
      }
    } else if (status == "rejected") {
      console.log("[handle] rejected")
      var ret = deferred.onRejected(cache);
      if (ret) {
        deferred.reject(ret);
      } else {
        deferred.reject(cache);
      }
    }
  }

  this.then = function(onFulfilled, onRejected) {
    return new Promise(function(resolve, reject) {
      console.log("[New Promise excutor] begin")
      handle({
        onFulfilled: onFulfilled,
        onRejected: onRejected,
        resolve: resolve,
        reject: reject
      }); // handle在handle定義的Promise中執(zhí)行如下操作
      // 如果當(dāng)前異步操作完成,將當(dāng)前異步操作的值作為onFulfilled參數(shù)調(diào)用,并調(diào)用resolve完成新Promise的異步操作 
      console.log("[New Promise excutor] finished")
    })
  }

  fn(resolve, reject);
  console.log("[In Promise] finished");
}

// var p1 = new Promise(function(resolve, reject){
//   console.log("[In executor function] start");
//   setTimeout(function(){
//     resolve(12);
//   }, 2000);
//   console.log("[In executor function] finish");
// })
// p1.then(function(v){console.log(v+1)});
// setTimeout(function() {
//   console.log("call then later");
//   p1.then(function(v){console.log(v-1)});
// }, 5000)
//var p2 = new Promise(function(resolve){
//  console.log("[In executor function] start");
//  resolve(12);
//  console.log("[In executor function] finish");
//})
//p2.then(function(v){console.log(v)});

var p3 = new Promise(function(resolve, reject){
  console.log("[In executor function] start");
  setTimeout(function(){
    reject("--[I throw an error]--");
  }, 2000);
  console.log("[In executor function] finish");
})
p3.then(function(v){
  console.log(v+1);
}, function(reason) {
  console.log(reason);
})
.then(function(v){
  console.log(v);
}, function(reason) {
  console.log("bubleup : ", reason);
});
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-16 01:19:06]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[handle] rejected
--[I throw an error]--
[handle] rejected
bubleup :  --[I throw an error]--

然而,如果是通過(guò)then注冊(cè)的回調(diào)出現(xiàn)錯(cuò)誤。。。

var p3 = new Promise(function(resolve, reject){
  console.log("[In executor function] start");
  setTimeout(function(){
    resolve(12);
  }, 2000);
  console.log("[In executor function] finish");
})
p3.then(function(v){
  console.log(v+1);
  throw "hehe, i'm broken";
}, function(reason) {
  console.log(reason);
})
.then(function(v){
  console.log(v);
}, function(reason) {
  console.log("bubleup : ", reason);
});
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-16 01:23:38]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[In Promise.resolve] start 12
[In Promise.resolve] finish
[handle] fulfilled
13

/home/reverland/tmp/Promise/promise.js:99
  throw "hehe, i'm broken";
  ^
hehe, i'm broken

稍微修改下:

  function handle(deferred) {
    if (status == "pending") {
      console.log("[handle] pending")
      dfs.push(deferred);
    } else if (status == "fulfilled") {
      console.log("[handle] fulfilled")
      try {
        var ret = deferred.onFulfilled(cache);
        if (ret) {
          deferred.resolve(ret);
        } else {
          deferred.resolve(cache);
        }
      } catch (e) {
        deferred.reject(e);
      }
    } else if (status == "rejected") {
      console.log("[handle] rejected")
      try {
        var ret = deferred.onRejected(cache);
        if (ret) {
          deferred.reject(ret);
        } else {
          deferred.reject(cache);
        }
      } catch (e) {
        deferred.reject(e)
      }
    }
  }
┌─[reverland@reverland-R478-R429] - [~/tmp/Promise] - [2015-10-16 01:27:34]
└─[0] <> node promise.js
[In Promise] start
[In executor function] start
[In executor function] finish
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[In Promise] start
[New Promise excutor] begin
[handle] pending
[New Promise excutor] finished
[In Promise] finished
[In Promise.resolve] start 12
[In Promise.resolve] finish
[handle] fulfilled
13
[handle] rejected
bubleup :  hehe, i'm broken

成功捕獲和冒泡錯(cuò)誤。

當(dāng)然,Promise規(guī)定啊then注冊(cè)的回調(diào)resolve和reject都是可選的,然而我并沒(méi)有處理,但通過(guò)以上試驗(yàn),知道了Promise的一些核心概念大致可以怎么實(shí)現(xiàn)。比如說(shuō),狀態(tài)、串行、失敗處理/失敗冒泡、異常處理。

綜上,最后發(fā)現(xiàn)沒(méi)寫(xiě)出啥新東西。你們還是看這里好理解——剖析 Promise 之基礎(chǔ)篇

參考

剖析 Promise 之基礎(chǔ)篇
JavaScript Promises ... In Wicked Detail
promiseaplus
es6 javascript promise 感性認(rèn)知

最后

美團(tuán)面試這么委婉拒絕我,呵呵

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容