Funkcia offers a concise and convenient way to write your code in a more imperative style that utilizes the native scope provided by the generator syntax. This syntax is more linear and resembles normal synchronous code.
Drawing primarily from Rust's ? operator for error propagation, and inspired by Gleam's use expressions, neverthrow's safeTry, and Effect's gen functions, the following functions provide a clean way to handle sequential operations while maintaining proper error handling and type safety.
use
Evaluates an async generator early returning when a Result.Error is propagated or returning the ResultAsync returned by the generator.
Each yield* automatically awaits and unwraps the ResultAsync value or propagates Error.
If any operation resolves to Result.Error, the entire generator exits early.
Returns a function that evaluates an async generator when called with the defined arguments, early returning when a Result.Error is propagated or returning the ResultAsync returned by the generator.
Each yield* automatically awaits and unwraps the ResultAsync value or propagates Error.
If any operation resolves to Result.Error, the entire generator exits early.
The use method provides a way to write sequential operations that might fail, similar to Rust's ? operator. It lets you write code that looks synchronous while safely handling potential failures.
It essentially creates a "safe context" where you can work with values as if they were guaranteed to exist, while maintaining all the safety guarantees of AsyncResult. If anything fails, the failure propagates automatically. Like an electronic relay that controls current flow, β relay controls computation flow: β Result.Ok continues, β Result.Error breaks the circuit.
Here's a practical example:
import { ResultAsync } from 'funkcia';
declare function rateLimit(clientId: ClientId, ip: IpAddress): ResultAsync<ClientId, RateLimitError>;
declare function findUserByEmail(email: Email): ResultAsync<User, UserNotFound>;
const userPreferences = ResultAsync.use(function* () {
// First, check if API rate limit is allowed
yield* rateLimit(req.headers['x-client-id'], req.ip);
// If rate-limit is not blocked, get the user
const user = yield* findUserByEmail(req.query.email);
// If all steps succeed, we can use the accumulated context to get user preferences
return ResultAsync.ok(user.preferences);
});
The equivalent code without use would be much more nested: