aboutsummaryrefslogtreecommitdiff
path: root/src/zilch/Promise.zig
diff options
context:
space:
mode:
authorNathan Reiner <nathan@nathanreiner.xyz>2026-10-17 10:13:13 +0200
committerNathan Reiner <nathan@nathanreiner.xyz>2026-10-17 10:13:13 +0200
commitb1b4df39abb41a4ae71733e2d139dc70cc71acd8 (patch)
tree3d72b1dd75841e0b950282099ec9c837aa03d869 /src/zilch/Promise.zig
parentdd24e86dad0402917b1713d1afeefaf65c3d1e51 (diff)
zilch: implement callable and promise
Diffstat (limited to 'src/zilch/Promise.zig')
-rw-r--r--src/zilch/Promise.zig54
1 files changed, 54 insertions, 0 deletions
diff --git a/src/zilch/Promise.zig b/src/zilch/Promise.zig
new file mode 100644
index 0000000..09654e3
--- /dev/null
+++ b/src/zilch/Promise.zig
@@ -0,0 +1,54 @@
+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: *Self, 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 fn as(self: *Self, T: type) *T {
+ return @ptrCast(self);
+}
+
+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 functions = [_]Function{
+ bindings.then,
+};