Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
import { Console, Effect } from "npm:effect";
const sucessfulProgram = Effect.sync(() => {
console.log("hi!");
return 42;
});
const main = Console.log("hi");
const num = Effect.succeed(2)
console.log("num effect", num);
Effect.runSync(main);
const divide = (a: number, b: number): Effect.Effect<number, Error, never> =>
b === 0
? Effect.fail(new Error("Cannot divide by zero"))
: Effect.succeed(a / b);
console.log("divide effect :", divide(10, 10));
const divisionResult = Effect.runSync(divide(10, 10));
console.log("division result :", divisionResult);
const failedProgram = Effect.try(() => {
throw new Error("boom");
return 42;
});
const asyncProgram = Effect.promise(() => Promise.resolve(42));
// just like functions, effects themselves are just values
// they don't do anything until you 'run' them
// console.log(sucessfulProgram);
// console.log(failedProgram);
// to run effects that are purely synchronous, use runSync
// it synchronously returns the result of the effect, or throws if the effect fails
const result = Effect.runSync(sucessfulProgram);
console.log("runSync result", result);
// try {
// Effect.runSync(failedProgram);
// } catch (error) {
// console.log("runSync error", error);
// }
// try {
// Effect.runSync(asyncProgram);
// } catch (error) {
// console.log("runSync async error", error);
// }
// if any part of your effect is asynchronous, you need to use runPromise
// it returns a promise that will resolve with the result of the effect,
// or reject if the effect fails
// Effect.runPromise(asyncProgram).then((result) => {
// console.log("runPromise result", result);
// });
// Effect.runPromise(failedProgram).catch((error) => {
// console.log("runPromise error", error);
// });
// as an alternative to simply throwing the error, the run*Exit functions
// provide a `Exit` type that represents either a success or a number of possible failure types
// const exit = Effect.runSyncExit(failedProgram);
// console.log("runSyncExit", exit);
June 6, 2024