-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync.ts
More file actions
70 lines (60 loc) · 1.5 KB
/
Copy pathasync.ts
File metadata and controls
70 lines (60 loc) · 1.5 KB
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
import {_, match} from '..';
let time = 0;
const delay = async (ms: number): Promise<void> => {
return new Promise(resolve => {
setTimeout(() => {
time += ms;
resolve();
}, ms);
});
};
type Something = {a: number, b: number};
function generateNumber() {
return 1 + Math.floor(Math.random() * 100);
}
async function doSomethingAsync(): Promise<Something> {
await delay(2000);
console.log(`[${time}] Generated some value`);
return {
a: generateNumber(),
b: generateNumber()
};
}
async function demo(): Promise<Something> {
const result = await doSomethingAsync();
return match<Something, Promise<Something>>(result).case(
[
({a}) => a % 2 == 1,
async result => {
console.log(`[${time}] a is odd`)
await delay(1000);
return result;
}
],
[
({b}) => b % 2 == 1,
async result => {
console.log(`[${time}] a is even, b is odd`)
await delay(1000);
return result;
}
],
[
_,
async result => {
console.log(`[${time}] Both a and b are even`)
await delay(1000);
return result;
}
]
);
}
console.log(`[${time}] Running demo`);
demo()
.then(result => console.log(`[${time}] Demo finished with result`, result))
.catch(err => console.error('An error has occurred', err));
// will exit with an output similar to:
// [0] Running demo
// [2000] Generated some value
// [2000] a is even, b is odd
// [3000] Demo finished with result { a: 52, b: 67 }