forked from chrisdavies/plite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plite.js
86 lines (72 loc) · 1.97 KB
/
plite.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function Plite() {
var result,
completed,
thenFn,
catchFn = function (err) { console.log(err); return err; },
finallyFn = function () { },
me;
function then(fn) {
var prevThen = thenFn || function (o, fn) { fn && fn(o); };
thenFn = function (o, then) {
prevThen(o, function (res) {
try {
result = fn(res);
if (!then) {
completed = true;
finallyFn(result);
} else if (result && result.then) {
result.then(then).catch(function (err) {
reject(err);
});
} else {
then(result);
}
} catch (err) {
reject(err);
}
});
};
completed && resolve(result);
return result && result.then ? result : me;
}
function _catch (fn) {
catchFn = fn;
return me;
}
function _finally (fn) {
finallyFn = fn;
completed && fn(result);
return me;
}
function resolve (obj) {
result = obj;
if (!(completed = (thenFn === undefined))) {
var fn = thenFn;
thenFn = undefined;
fn(obj);
} else {
finallyFn(result);
}
}
function reject (err) {
result = err;
then = function () { return this; };
result = catchFn(result);
finallyFn(result);
function callInstantly(fn) {
fn(result);
return this;
}
me.catch = me.finally = function (fn) {
result = fn(result);
return this;
}
}
return me = {
'catch': _catch,
'finally': _finally,
then: then,
reject: reject,
resolve: resolve
}
}