-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathProgram.cs
More file actions
51 lines (42 loc) · 1.22 KB
/
Copy pathProgram.cs
File metadata and controls
51 lines (42 loc) · 1.22 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
using HakoJS;
using HakoJS.Backend.Wasmtime;
using HakoJS.Extensions;
// Initialize the runtime
var runtime = Hako.Initialize<WasmtimeEngine>();
// Create a realm (isolated JS execution context)
var realm = runtime.CreateRealm().WithGlobals(g => g.WithConsole());
// Synchronous evaluation
var syncResult = realm.EvalCode("2 + 2");
Console.WriteLine($"2 + 2 = {syncResult.Unwrap().AsNumber()}");
syncResult.Dispose();
// Async evaluation automatically handles promises
var promiseResult = await realm.EvalAsync<int>("Promise.resolve(42)");
Console.WriteLine($"Promise resolved to: {promiseResult}");
// Working with objects
var obj = await realm.EvalAsync(@"
const user = {
name: 'Alice',
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
}
};
user;
");
var name = obj.GetPropertyOrDefault<string>("name");
var greeting = obj.GetProperty("greet");
Console.WriteLine($"{name}: {greeting.Invoke()}");
greeting.Dispose();
obj.Dispose();
// Error handling with try-catch
try
{
await realm.EvalAsync("Promise.reject('oops')");
}
catch (Exception ex)
{
Console.WriteLine($"Caught: {ex.InnerException?.Message}");
}
realm.Dispose();
runtime.Dispose();
await Hako.ShutdownAsync();