This repository has been archived by the owner on Dec 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phen.js
88 lines (70 loc) · 1.8 KB
/
phen.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
87
/*!
* (c) 2015 Towry Wang
* Released under MIT License
*
* Browser side Promise implemented.
*/
!function (global) {
global.phen = {
defer: function (fn) {
if (!fn || typeof fn !== 'function') {
throw new Error("Expecting a function as argument");
}
return new Promise(fn);
}
}
/*
* A promise object has three states: pending, fulfilled, rejected
*/
function Promise (fn) {
var pending = [], value, state = 'pending', self = this;
var proto = Promise.prototype;
proto.then = function (onFulfilled, onRejected) {
onFulfilled = onFulfilled || function (v) {
return v;
}
onRejected = onRejected || function (e) {
return e;
}
return new Promise(function (resolve, reject) {
var _onFulfilled = function (v) {
resolve(onFulfilled(v));
}
var _onReject = function (e) {
resolve(onRejected(e));
}
if (state !== 'pending') {
_onFulfilled(value);
}
else {
pending.push([_onFulfilled, _onReject]);
}
});
}
setTimeout(function () {
fn(function (v) {
// resolve it, after resolve, the promise is fulfilled
value = v;
if (pending) {
for (var i = 0, ii = pending.length; i < ii; i++) {
var cb = pending[i][0];
cb(v);
}
pending = null;
}
state = 'fulfilled';
}, function (e) {
// reject it, after reject, the promise is rejected
value = e;
if (pending) {
for (var i = 0, ii = pending.length; i < ii; i++) {
var cb = pending[i][1];
cb(e);
}
pending = null;
}
state = 'rejected';
});
}, 1);
}
}(window);