-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAA.res
126 lines (99 loc) · 2.4 KB
/
AA.res
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
type testable = (. unit) => Js.Promise.t<unit>
let tests: array<testable> = []
let addTest = t => tests->Js.Array2.push(t)->ignore
let addTest1 = (t, x) => tests->Js.Array2.push((. ()) => t(. x))->ignore
//
//
// Basic tests
let foo = @async (. x, y) => x + y
let bar =
@async
(. ff) => {
let a = @await ff(. 3, 4)
let b = @await foo(. 5, 6)
a + b
}
let baz = @async (. ()) => @await bar(. foo)
let testBaz: testable =
@async
(. ()) => {
let n = @await baz(.)
Js.log2("baz returned", n)
}
testBaz->addTest
//
//
// Catching exceptions
exception E(int)
let e1: testable = @async (. ()) => raise(E(1000))
let e2: testable = @async (. ()) => Js.Exn.raiseError("Some JS error")
let e3: testable = @async (. ()) => @await e1(.)
let e4: testable = @async (. ()) => @await e2(.)
let e5: testable = %raw(`function() { return Promise.reject(new Error('fail')) }`)
let testTryCatch =
@async
(. fn) =>
try @await
fn(.) catch {
| E(n) => Js.log2("testTryCatch: E", n)
| JsError(_) => Js.log("testTryCatch: JsError")
}
testTryCatch->addTest1(e1)
testTryCatch->addTest1(e2)
testTryCatch->addTest1(e3)
testTryCatch->addTest1(e4)
testTryCatch->addTest1(e5)
//
//
// Check for nested promise
let singlePromise = @async (. x) => x + 1
let nestedPromise =
@async
(. x) => {
let resolve = x => [Js.Promise.resolve(x)]
let _result = singlePromise(. x + 1)->resolve
32
}
//
//
// Test error handling in fetch
let explainError: unknown => string = %raw(`(e)=>e.toString()`)
let testFetch =
@async
(. url) => {
switch @await
Fetch.fetch(url) {
| response =>
let status = response->Fetch.Response.status
Js.log2("Fetch returned status:", status)
| exception JsError(e) => Js.log2("Fetch returned an error:", e->explainError)
}
}
testFetch->addTest1("https://www.google.com/sdkjdkghdsg")
testFetch->addTest1("https://www.google.comsdkjdkghdsg")
//
//
// Callbacks
let withCallback =
@async
(. ()) => {
let callback = @async (. x) => @await (x->Js.Promise.resolve) + 1
callback
}
let testWithCallback =
@async (. ()) => Js.log2("callback returned", @await (@await withCallback(.))(. 3))
testWithCallback->addTest
//
//
// Run tests
let rec runAllTests =
@async
(. n) => {
if n >= 0 && n < Array.length(tests) {
@await
tests[n](.)
@await
runAllTests(. n + 1)
}
}
runAllTests(. 0)->ignore