-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPromise.js
74 lines (63 loc) · 1.76 KB
/
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
(function () {
const pending = 0;
const fulfilled = 1;
const chained = 2;
const is_function = x => typeof x === 'function';
const no_op = () => {};
function Promise(executor) {
this.state = pending;
this.value = undefined;
this.handlers = [];
executor(value => {
if (this.state != pending) return;
resolve(this, value);
});
}
const resolve_or_wait = (self, handler) => {
while (self.state === chained) {
self = self.value;
}
if (self.state === pending) {
self.handlers.push(handler);
}
else {
setTimeout(() => {
const on_fulfilled = handler.on_fulfilled;
resolve(handler.promise, on_fulfilled === null ? self.value : on_fulfilled(self.value));
});
}
};
const resolve = (self, value) => {
if (value === self) {
throw new TypeError('A promise cannot be resolved with itself.');
}
self.state = value instanceof Promise ? chained : fulfilled;
self.value = value;
for (let i = 0, len = self.handlers.length; i < len; ++i) {
resolve_or_wait(self, self.handlers[i]);
}
self.handlers = null;
};
Promise.prototype.then = function (on_fulfilled) {
const p = new Promise(no_op);
resolve_or_wait(this, {
on_fulfilled: is_function(on_fulfilled) ? on_fulfilled : null,
promise: p,
});
return p;
};
Promise.resolve = value =>
value instanceof Promise ?
value :
new Promise(resolve => resolve(value));
Promise.race = arr =>
new Promise(resolve => {
if (!Array.isArray(arr)) {
throw 'Promise.race only accepts an array';
}
for (let i = 0, len = arr.length; i < len; ++i) {
Promise.resolve(arr[i]).then(resolve);
}
});
module.exports = Promise;
})();