Skip to content

Commit 0f7cdca

Browse files
author
陈亮16
committed
[feat]最简版deferred
1 parent b04fe4f commit 0f7cdca

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

JS/simulate-deferred.js

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// https://github.com/mochi/mochikit/blob/master/MochiKit/Async.js
2+
// JavaScript 框架设计 chapter12
3+
Deferred = function(canceller){
4+
this.state = -1;
5+
this.fired = 0;
6+
this.results = [null, null];
7+
this.paused = 0;
8+
this.chain = [];
9+
this.canceller = canceller;
10+
this.silentlyCancelled = false;
11+
}
12+
13+
Deferred.prototype = {
14+
state: function(){
15+
return ['unfired', 'success', 'error'][this.state + 1];
16+
},
17+
_check: function(){
18+
19+
},
20+
_errback: function(){
21+
22+
},
23+
_resback: function(){
24+
25+
},
26+
callback: function(res){
27+
this._check();
28+
if(res instanceof Deferred){
29+
throw new Error("不能调用 Deferred 作为 Deferred 参数");
30+
}
31+
this._resback(res);
32+
},
33+
addCallbacks: function(sucCall, errCall){
34+
errCall = errCall || sucCall;
35+
this.chain.push([sucCall, errCall]);
36+
if(this.fired >= 0){
37+
this._fire();
38+
}
39+
return this;
40+
},
41+
_fire: function(){
42+
var chain = this.chain,
43+
fired = this.fired,
44+
res = this.results[fired],
45+
self = this,
46+
cb = null;
47+
while(chain.length > 0 && this.paused === 0){
48+
var pair = chain.shift();
49+
var f = pair[fired];
50+
if(f === null){
51+
continue;
52+
}
53+
try{
54+
res = f(res);
55+
fired = res instanceof Error ? 1 : 0;
56+
// if(res instanceof Deferred){
57+
// cb = function(res){
58+
59+
// }
60+
// }
61+
}catch(err){
62+
fired = 1;
63+
res = err;
64+
}
65+
}
66+
this.fired = fired;
67+
this.results[fired] = res;
68+
// if(cb && this.paused){
69+
70+
// }
71+
72+
}
73+
74+
}

JS/simulate-deferred.test.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use strict'
2+
var deferred = require('./simulate-deferred');
3+
function increment(value){
4+
console.log(value);
5+
return value + 1;
6+
}
7+
8+
var d = new Deferred();
9+
d.addCallbacks(increment)
10+
d.addCallbacks(increment)
11+
d.addCallbacks(increment)
12+
d.callback(1)

0 commit comments

Comments
 (0)