-
Notifications
You must be signed in to change notification settings - Fork 0
/
promises_ES6.js
120 lines (102 loc) · 3.05 KB
/
promises_ES6.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class Promise {
constructor(executor) {
if (!isFunction(executor)) {
throw new TypeError("executor must be a function");
}
this.value = null;
this.reason = null;
this.state = "pending";
this.fulfilReactions = [];
this.rejectReactions = [];
try {
executor(x => resolve(this, x), x => reject(this, x));
} catch (e) {
reject(this, e);
}
}
then(onFulfilled, onRejected) {
return new Promise((resolve, reject) => {
function safelyResolve(callback, x) {
try {
resolve(callback(x));
} catch (e) {
reject(e);
}
}
if (!isFunction(onFulfilled)) {
onFulfilled = value => value;
}
if (!isFunction(onRejected)) {
onRejected = reason => reject(reason);
}
if (this.state === "pending") {
this.fulfilReactions.push(x => safelyResolve(onFulfilled, x));
this.rejectReactions.push(x => safelyResolve(onRejected, x));
} else if (this.state === "fulfilled") {
async(() => safelyResolve(onFulfilled, this.value));
} else if (this.state === "rejected") {
async(() => safelyResolve(onRejected, this.reason));
}
});
}
static resolve(x) {
return new Promise(resolve => resolve(x));
}
static reject(x) {
return new Promise((_, reject) => reject(x));
}
}
function resolve(promise, x) {
if (promise.state === "pending") {
try {
var then = x.then;
} catch (e) {
reject(promise, e);
}
if (typeof x === "object" && typeof then === "function") {
resolveThenable(promise, x, then);
} else {
fulfil(promise, x);
}
}
}
function fulfil(promise, x) {
promise.state = "fulfilled";
promise.value = x;
promise.fulfilReactions.forEach(reaction => async(() => reaction(x)));
}
function reject(promise, x) {
if (promise.state === "pending") {
promise.state = "rejected";
promise.reason = x;
promise.rejectReactions.forEach(reaction => async(() => reaction(x)));
}
}
function resolveThenable(promise, thenable, then) {
if (thenable === promise) {
reject(promise, new TypeError("Can't resolve a promise with itself"));
}
var called = false;
try {
then.call(thenable, function resolvePromise(x) {
if (called) return;
called = true;
return resolve(promise, x);
}, function rejectPromise(x) {
if (called) return;
called = true;
return reject(promise, x);
});
} catch (e) {
if (called) return;
called = true;
return reject(promise, e);
}
}
function isFunction(a) {
return typeof a === "function";
}
function async(fn) {
setTimeout(fn, 0);
}
module.exports = Promise;