简单实现Promise

前几天看一本书,叫做《Neural Network and Deep Learning》. 这本书中介绍了神经网络一些很神奇的概念,最特色的是,难得有人去思考和追究这一切看上去似乎很好的概念最开始是怎么来的,为什么我们会想到这种东西?

每当我看到javascript中的Promise也是这么想,这种设计?难道是天上掉下来的,最初的人们到底是怎么想到这种规范的呢?然而大多数人并不讨论这些东西,我们不用知道历史和原理,就能自由使用Promise。就像神经网络中,你不用知道为什么人们会发现L1 and L2 regularization,也不用想sigmoid函数为什么会被选中,按照推出的公式就能很好的使用它。

但对某些人来说,我们还是好奇,它为啥会出现,它怎么实现的?

我只是自己做着玩,读者不用太认真。如果有指教,欢迎ping me。

历史

Javascript中Promise的来源

实现

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

我们先看看,需要新建一个Promise对象,这个对象构建时接受一个函数。

这个函数中是一个异步操作,即在5秒之后,才会返回

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这个Promise的时候,给了它一个函数作为参数,这个函数叫做executor函数,接受两个参数,分别对应Promise函数里定义的resolve和reject。一种约定。

我们在这个executor里异步调用resolve函数,直到某个时刻之后,才给他一个值12. 一个典型的异步操作。

通过以上机制,我们构建了一个Promise对象,这个Promise能处理我们在executor函数中未来某个时刻的异步返回,返回值之后交给我们通过then绑定到Promise中的函数(cbs)来处理(由Promise类中定义的resolve实现)。

但是,如果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

没反应了就。。。因为,cb没东西的时候程序就运行完了。。。

所以,重新实现 Promise类中的resolve函数,用setTimeout将Promise.resolve强行置于同步代码(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

我觉得挺好。。。好像没有问题的样子

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

消失了?只能调用一次?当你通过then往cbs里注册回调的时候,executor里的异步调用已经返回,resolve已经执行了。

Promise对象应该缓存异步返回的值,让接下来的then可以直接调用。

所以要引入状态和缓存

function Promise(fn) {
  console.log("[In Promise] start");
  this.__name__ = "My promise";
  var cbs = []; // 因为我想then好几次
  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

这就对了。接下来,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方法没有返回。

为了衔接当前Promise和下一个,then函数返回一个Bridge Promise,Bridge Promise的executor函数做了以下事情:

  • 如果当前Promise fulfilled的话就调用then函数的参数中的callback,并把当前Promise异步返回的值作为参数传入。调用Bridge Promise的resolve让Bridge Promise进入fulfill状态。
  • 如果当前Promise没有fulfilled就在队列中添加回调。

我们重新确认下,Promise的原理。对executor中的异步返回,我们把它传给Promise的resolve方法。该方法负责将用then注册的回调队列执行(如果不是pending状态),并传入异步返回值作为参数。

而串联的时候则是,返回新的Promise,该Promise的executor中用当前Promise注册的callback和新Promise的resolve来实现将注册callback返回的值送给新的Promise的resolve来完成新的Promise状态转变为fulfilled这么一个过程。

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中执行如下操作
     // 如果当前异步操作完成,将当前异步操作的值作为callback参数调用,并调用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。

然而还是有问题,我们想,如果,then绑定的函数没有返回,则默认将上次返回值继续下传。现在却是直接向下一步返回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

看上去非常好!接着是错误冒泡,跟之前完全类似

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中执行如下操作
      // 如果当前异步操作完成,将当前异步操作的值作为onFulfilled参数调用,并调用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]--

然而,如果是通过then注册的回调出现错误。。。

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

成功捕获和冒泡错误。

当然,Promise规定啊then注册的回调resolve和reject都是可选的,然而我并没有处理,但通过以上试验,知道了Promise的一些核心概念大致可以怎么实现。比如说,状态、串行、失败处理/失败冒泡、异常处理。

综上,最后发现没写出啥新东西。你们还是看这里好理解——剖析 Promise 之基础篇

参考

剖析 Promise 之基础篇
JavaScript Promises ... In Wicked Detail
promiseaplus
es6 javascript promise 感性认知

最后

美团面试这么委婉拒绝我,呵呵

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容