zigar.function.Promise(T).partition(self, allocator, count) - chung-leong/zigar GitHub Wiki

Create a new promise that is fulfilled only after its resolve() method has been called a number of times. In effect, this function splits a promise into multiple parts.

An error would cause immediate rejection.

Memory allocated for the promise's storage is freed when it's resolved.

Usage:

const std = @import("std");
const zigar = @import("zigar");

const Error = error{ SaltInCoffee, CannotLoseWeight };
const Promise = zigar.function.Promise(Error!usize);
var gpa = std.heap.DebugAllocator(.{}).init;
const allocator = gpa.allocator();

pub fn get1(promise: Promise) !void {
    const multipart_promise = try promise.partition(allocator, 10);
    for (0..10) |i| {
        multipart_promise.resolve(i);
    }
}

pub fn get2(promise: Promise) !void {
    const multipart_promise = try promise.partition(allocator, 10);
    for (0..10) |i| {
        multipart_promise.resolve(switch (i) {
            3 => error.SaltInCoffee,
            5 => error.CannotLoseWeight,
            else => i,
        });
    }
}
import { get1, get2 } from './promise-example-9.zig';

console.log(await get1());
try {
    await get2();
} catch (err) {
    console.log(err.message);
}
9
Salt in coffee

Arguments:

  • self: @This()
  • allocator: std.mem.Allocator
    Allocator used to obtain and free memory for the new promise object.
  • count: usize
    The number of times the new promise object's resolve() method needs to be called before the original promise is fulfilled.

Return value:

  • error{OutOfMemory}|Promise(T)

Promise(T)