blob: 141253271a1c20f396e8b10cd5195ddcb5dd3850 (
plain)
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
|
"use strict";
/* ------------------------------------------------------------------------ */
module.exports = class SyncPromise {
constructor (fn) {
try {
fn (
x => { this.setValue (x, false) }, // resolve
x => { this.setValue (x, true) } // reject
)
} catch (e) {
this.setValue (e, true)
}
}
setValue (x, rejected) {
this.val = (x instanceof SyncPromise) ? x.val : x
this.rejected = rejected || ((x instanceof SyncPromise) ? x.rejected : false)
}
static valueFrom (x) {
if (x instanceof SyncPromise) {
if (x.rejected) throw x.val
else return x.val
} else {
return x
}
}
then (fn) {
try { if (!this.rejected) return SyncPromise.resolve (fn (this.val)) }
catch (e) { return SyncPromise.reject (e) }
return this
}
catch (fn) {
try { if (this.rejected) return SyncPromise.resolve (fn (this.val)) }
catch (e) { return SyncPromise.reject (e) }
return this
}
static resolve (x) {
return new SyncPromise (resolve => { resolve (x) })
}
static reject (x) {
return new SyncPromise ((_, reject) => { reject (x) })
}
}
|