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 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, };