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
|
const std = @import("std");
const mod = @import("root.zig");
const Env = mod.Env;
const Future = Env.Future;
const Function = Env.Function;
const Object = mod.Object;
const Value = mod.Value;
const Self = @This();
// NOTE: js runs only on one thread, so this is safe,
// else an allocation would be necessary!
var promise_value: Value = undefined;
pub inline fn then(self: anytype, env: *Env, func: anytype, ud: *anyopaque) Future(void) {
const wrapper = struct {
fn wrapper(userdata: *anyopaque) callconv(.c) void {
const args = @typeInfo(@TypeOf(func)).@"fn".params;
const value = promise_value.unwrap(args[1].type orelse void);
func(@alignCast(@ptrCast(userdata)), value) catch |err| {
std.log.err("{}", .{err});
@panic("error handling promise");
};
}
}.wrapper;
return .fromAny(env.call(bindings.then, .{
self,
@intFromPtr(&wrapper),
@intFromPtr(&promise_value),
@intFromPtr(ud),
}));
}
pub inline fn await(self: anytype, env: *Env, T: type) !T {
var future = env.call(bindings.await, .{ self });
return future.await(env, T);
}
pub const bindings = struct {
pub const then: Function = .from(
\\function(promise, func, ptr, ud) {
\\ promise.then((value) => {
\\ ObjectStore.writeValue(ptr, value);
\\ wasm.exports.__indirect_function_table.get(func)(ud);
\\ })
\\}
);
pub const await: Function = .from(
\\async function(promise) {
\\ return promise;
\\}
);
};
pub const functions = [_]Function{
bindings.then,
bindings.await,
};
|