-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtiny-promise.js
99 lines (88 loc) · 3 KB
/
tiny-promise.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
88
89
90
91
92
93
94
95
96
97
98
99
/* tiny-promise.js v1.0.0 Licensed under the MIT license. (c) 2014 rtsan */
(function(root, factory) {
if (typeof module !== 'undefined' &&
typeof module.exports !== 'undefined') {
exports = module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define([], factory);
} else {
root.Promise = factory();
}
}(this, function(undef) {
function _resolve(promise, x) {
var then, proxy;
if (promise === x) {
return promise.reject(new TypeError());
}
try {
if (typeof x === 'function') {
then = x.then || x;
} else if (typeof x === 'object' && x !== null) {
then = x.then;
}
} catch (err) {
return promise.reject(err);
}
// The idea is from "Promises, Promises..." http://promises.codeplex.com
if (typeof then === 'function') {
proxy = Promise();
proxy.then(function(v) {
_resolve(promise, v);
}, promise.reject);
try {
then.call(x, proxy.resolve, proxy.reject);
} catch (err) {
proxy.reject(err);
}
} else {
promise.resolve(x);
}
}
function Promise() {
var fulfilled,
_ = {},
chains = [],
decide = function(status, decision) {
if (!fulfilled) {
fulfilled = true;
_.status = status;
_.decision = decision;
while (chains.length) {
(chains.shift())();
}
}
},
chain = function(next, onfulfilled, onrejected) {
return function() {
setTimeout(function() {
var then = (_.status ? onfulfilled : onrejected),
propagate = (_.status ? next.resolve : next.reject);
try {
if (typeof then === 'function') {
_resolve(next, then.call(undef, _.decision));
} else {
propagate(_.decision);
}
} catch (err) {
next.reject(err);
}
}, 1);
};
};
return {
resolve: function(value) { decide(true, value); },
reject: function(reason) { decide(false, reason); },
then: function(onfulfilled, onrejected) {
var next = Promise(),
chained = chain(next, onfulfilled, onrejected);
if (fulfilled) {
chained();
} else {
chains.push(chained);
}
return next;
}
};
}
return Promise;
}));