-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (67 loc) · 1.58 KB
/
index.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
import {
resolve,
reject,
PENDING,
FULFILLED,
invokeCallback,
subscribe
} from './src/core';
import {
needResolver,
needNew,
isFunction,
noop,
nextId
} from './src/utils';
import asap from './src/asap';
import originalResolve from './src/promise/resolve';
import originReject from './src/promise/reject';
import race from './src/promise/race';
function checkResolver(resolver) {
return isFunction(resolver) || needResolver();
}
function checkNew(x) {
return x instanceof Promise || needNew()
}
class Promise {
constructor(resolver) {
this._ID = nextId();
this._result = undefined;
this._state = undefined;
this._subscribers = [];
if (checkResolver(resolver) && checkNew(this)) {
// 执行resolver
try {
resolver(
value => resolve(this, value),
reason => reject(this, reason)
)
} catch(e) {
reject(this, e);
}
}
}
then(onFulfillment, onRejection) {
const parent = this;
const child = new this.constructor(noop);
if (parent._state !== PENDING) {
const callback = parent._state === FULFILLED ? onFulfillment : onRejection;
asap(() => {
invokeCallback(child, parent._state, callback, parent._result);
})
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
catch(onRejection) {
return this.then(null, onRejection);
}
finally(callback) {
return this.then(callback, callback)
}
}
Promise.resolve = originalResolve;
Promise.reject = originReject;
Promise.race = race;
export default Promise;