-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (71 loc) · 1.82 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
class __Promise {
constructor(executor) {
this.state = 'pending'
this.value = undefined
this.queue = []
const transitionTo = state => v => {
if (this.state !== 'pending') return
this.state = state
this.value = v
this.queue.forEach(f => f())
}
try {
executor(transitionTo('fulfilled'), transitionTo('rejected'))
} catch (e) {
transitionTo('rejected')(e)
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
onRejected = typeof onRejected === 'function' ? onRejected : e => { throw e }
const promise2 = new __Promise((resolve, reject) => {
const fn = () => {
setTimeout(() => {
try {
const cb = this.state === 'fulfilled' ? onFulfilled : onRejected
promiseResolve(promise2, cb(this.value), resolve, reject)
} catch (e) {
reject(e)
}
})
}
if (this.state === 'pending') {
this.queue.push(fn)
} else {
fn()
}
})
return promise2
}
}
function promiseResolve(promise2, x, resolve, reject) {
if (x === promise2) return reject(new TypeError('Chaining cycle detected for promise'))
//2.3.3.3.3
let called = false;
let once = (fn) => {
if (called) return
called = true
fn()
}
if (x != null && (typeof x === 'object' || typeof x === 'function')) {
try {
const then = x.then
if (typeof then === 'function') {
then.call(
x,
//2.3.3.3.3
y => once(() => promiseResolve(promise2, y, resolve, reject)),
r => once(() => reject(r))
)
} else {
resolve(x)
}
} catch (e) {
//2.3.3.3.4.1
once(() => reject(e))
}
} else {
resolve(x)
}
}
module.exports = __Promise