-
Notifications
You must be signed in to change notification settings - Fork 3
zigar.function.Promise(T).init(ptr, cb)
Chung Leong edited this page Mar 19, 2025
·
5 revisions
Initialize a promise struct using the given pointer and function reference.
Usage
const std = @import("std");
const zigar = @import("zigar");
const Promise = zigar.function.Promise([]const u8);
var gpa = std.heap.DebugAllocator(.{}).init;
const allocator = gpa.allocator();
const Response = struct {
name: []u8,
pub fn onResult(self: *@This(), text: []const u8) void {
std.debug.print("{s}: {s}\n", .{ self.name, text });
allocator.free(self.name);
allocator.destroy(self);
}
};
pub fn call(cb: *const fn (Promise) void) !void {
const response = try allocator.create(Response);
response.name = try allocator.dupe(u8, "Bart");
const promise = Promise.init(response, Response.onResult);
cb(promise);
}
import { call } from './promise-example-8.zig';
call(async () => 'Eat my shorts!');
Bart: Eat my shorts!
Arguments:
-
ptr
:?*const anyopaque
Basically any pointer--ornull
. If aconst
pointer is given, it's@constCast()
to*anyopaque
, with the expectation thatcb
will take a matchingconst
pointer. -
callback
:anytype
A function or a pointer to one that accepts a pointer as the first argument andT
as the second. For convenience sake the first argument can be any single pointer. It does not need to be?*anyopaque
. Any pointer, optional or not, will do.
Return value:
Promise(T)