简单实现Promise
前几天看一本书,叫做《Neural Network and Deep Learning》. 这本书中介绍了神经网络一些很神奇的概念,最特色的是,难得有人去思考和追究这一切看上去似乎很好的概念最开始是怎么来的,为什么我们会想到这种东西?
每当我看到javascript中的Promise也是这么想,这种设计?难道是天上掉下来的,最初的人们到底是怎么想到这种规范的呢?然而大多数人并不讨论这些东西,我们不用知道历史和原理,就能自由使用Promise。就像神经网络中,你不用知道为什么人们会发现L1 and L2 regularization,也不用想sigmoid函数为什么会被选中,按照推出的公式就能很好的使用它。
但对某些人来说,我们还是好奇,它为啥会出现,它怎么实现的?
我只是自己做着玩,读者不用太认真。如果有指教,欢迎ping me。
历史
实现
首先,你得知道闭包是什么。
我们先看看,需要新建一个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 感性认知
最后
美团面试这么委婉拒绝我,呵呵