-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (74 loc) · 2.05 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
80
81
82
const Status = { Pending: 'PENDING', Fulfilled: 'FULFILLED', Rejected: 'REJECTED' }
const id = v => v
const idThrow = e => {
throw e
}
class Nuo {
constructor(executor) {
this.state = Status.Pending
this.value = undefined
this.queue = []
const transitionTo = state => x => {
if (this.state === Status.Pending) {
this.state = state
this.value = x
this.queue.forEach(f => f())
}
}
try {
executor(transitionTo(Status.Fulfilled), transitionTo(Status.Rejected))
} catch (e) {
transitionTo(Status.Rejected)(e)
}
}
then(onResolved, onRejected) {
onResolved = typeof onResolved === 'function' ? onResolved : id
onRejected = typeof onRejected === 'function' ? onRejected : idThrow
const promise2 = new Nuo((resolve, reject) => {
const schedulePromise2Resolution = () => {
setTimeout(() => {
try {
const cb = this.state === Status.Fulfilled ? onResolved : onRejected
resolvePromise(promise2, cb(this.value), resolve, reject)
} catch (e) {
reject(e)
}
})
}
if (this.state === Status.Pending) {
this.queue.push(schedulePromise2Resolution)
} else {
schedulePromise2Resolution()
}
})
return promise2
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (x === promise2) return reject(new TypeError('Chaining cycle detected for promise'))
let called
const guard = fn => {
if (called) return
called = true
fn()
}
if (x != null && (typeof x === 'object' || typeof x === 'function')) {
try {
const then = x.then // x.then should only be called once since it may be a getter
if (typeof then === 'function') {
then.call(
x,
y => guard(() => resolvePromise(promise2, y, resolve, reject)),
err => guard(() => reject(err))
)
} else {
resolve(x)
}
} catch (e) {
guard(() => reject(e))
}
} else {
resolve(x)
}
} // 80 LOC
module.exports = Nuo