Do Notation
A do notation
syntax allows writing code in a more declarative style, similar to the do notation
in other programming languages. It provides a way to define variables and perform operations on them using functions like bind
and let
, piping the returned values into a context object.
Do
Initiates a do notation
for the Result
type.
import { AsyncResult } from 'funkcia';
declare function findUserById(id: string): AsyncResult;
declare function calculateUserScore(user: User): AsyncResult;
declare function rankUserLevel(user: User, score: UserScore): AsyncResult;
// ┌─── AsyncResult
// â–¼
const userLevel = AsyncResult.Do
.bind('user', () => findUserById('user_123'))
.bind('score', () => calculateUserScore(ctx.user))
.map((ctx) => rankUserLevel(ctx.user, ctx.score));
// â–²
// └─── { user: User; score: UserScore }
bindTo
Initiates a do notation
with the current AsyncResult
, binding it to a context object with the provided key.
import { AsyncResult } from 'funkcia';
declare function findUserById(id: string): AsyncResult;
declare function calculateUserScore(user: User): AsyncResult;
declare function rankUserLevel(user: User, score: UserScore): AsyncResult;
// ┌─── AsyncResult
// â–¼
const userLevel = findUserById('user_123')
.bindTo('user')
.bind('score', () => calculateUserScore(ctx.user))
.map((ctx) => rankUserLevel(ctx.user, ctx.score));
// â–²
// └─── { user: User; score: UserScore }
bind
Binds an AsyncResult
to the context object in a do notation
.
If the Result
is Ok
, the value is assigned to the key in the context object. If the Result
is Error
, the parent Result
running the Do
simulation becomes an Error
.
import { AsyncResult } from 'funkcia';
declare function findUserById(id: string): AsyncResult;
declare function calculateUserScore(user: User): AsyncResult;
declare function rankUserLevel(user: User, score: UserScore): AsyncResult;
// ┌─── Result
// â–¼
const userLevel = AsyncResult.Do
.bind('user', () => findUserById('user_123'))
.bind('score', () => calculateUserScore(ctx.user))
.map((ctx) => rankUserLevel(ctx.user, ctx.score));
// â–²
// └─── { user: User; score: UserScore }
let
Ensure you know what you're doing when binding a promise using let
, otherwise a thrown exception will not be caught and break your app
Binds non-rejecting promise to the context object in a do notation
.
import { AsyncResult } from 'funkcia';
// ┌─── AsyncResult
// â–¼
const result = AsyncResult.Do
.let('a', () => Promise.resolve(10))
.let('b', () => Promise.resolve(ctx.a * 2))
.map((ctx) => a + b);
// â–²
// └─── { a: number; b: number }
Understanding the do notation
Do notation provides a clean way to handle sequences of operations that might fail, where each step depends on the success of all previous steps. Think of it as a chain of dominoes - if any domino falls incorrectly (returns None
), the entire sequence stops.
Here's a practical example:
import { AsyncResult } from 'funkcia';
declare function findUser(id: string): AsyncResult<User, UserNotFound>;
declare function getUserPermissions(user: User): AsyncResult<Permissions, MissingPermissionsError>;
declare function checkAccess(permissions: Permissions, resource: string): AsyncResult<Access, InsuficientPermissionsError>;
const access = AsyncResult.Do
// First, try to find the user
.bind('user', () => findUser('user_123'))
// If user is found, get their permissions
.bind('permissions', (ctx) => getUserPermissions(ctx.user))
// If all steps succeed, we can use the accumulated context to check access to specific resource
.andThen((ctx) => checkAccess(ctx.permissions, 'api-key'));
The equivalent code would be much more nested:
import { AsyncResult } from 'funkcia';
declare function findUser(id: string): AsyncResult<User, UserNotFound>;
declare function getUserPermissions(user: User): AsyncResult<Permissions, MissingPermissionsError>;
declare function checkAccess(permissions: Permissions, resource: string): AsyncResult<Access, InsuficientPermissionsError>;
const access = findUser('user_123')
.andThen(user =>
getUserPermissions(user)
.andThen(permissions =>
checkAccess(permissions, 'api-key')
)
);
Or with intermediate variables:
import { AsyncResult } from 'funkcia';
declare function findUser(id: string): AsyncResult<User, UserNotFound>;
declare function getUserPermissions(user: User): AsyncResult<Permissions, MissingPermissionsError>;
declare function checkAccess(permissions: Permissions, resource: string): AsyncResult<Access, InsuficientPermissionsError>;
const user = findUser('user_123');
const permissions = user.andThen(getUserPermissions);
const access = permissions.andThen(permissions => {
return checkAccess(permissions, 'admin-panel');
});
Last updated
Was this helpful?