zigar.function.Promise(T).init(ptr, cb) ᴾᴴᴾ - chung-leong/zigar GitHub Wiki

JavaScript | PHP


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);
}
<?php

$m = zigar_use(__DIR__ . '/promise-example-8.zig');

$m->call(function() {
    return 'Eat my shorts!';
});
Bart: Eat my shorts!

Arguments:

  • ptr: ?*const anyopaque
    Basically any pointer--or null. If a const pointer is given, it's @constCast() to *anyopaque, with the expectation that cb will take a matching const pointer.
  • callback: anytype
    A function or a pointer to one that accepts a pointer as the first argument and T 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)


Promise(T)