Skip to content

create

create<E, A, I>(factory, onError): Op<I, E, A>

Defined in: Core/Op.ts:487

Creates an Op from an async factory and an error mapper.

The factory receives an AbortSignal and returns a function that takes the input. Capture the signal in the outer closure and pass it to cancellable APIs like fetch. The error mapper converts any thrown value into a typed error; it is never called for aborts.

If the factory ignores the signal, cancellation silently stops working: the operation runs to completion and emits Ok even after the strategy has aborted it. This is harmless for exclusive and once (which do not abort in-flight work), but causes stale Ok emissions on restartable, debounced, throttled, buffered, and queue strategies where in-flight runs are regularly replaced or dropped.

E

A

I = void

(signal) => (input) => Promise<A>

(e) => E

Op<I, E, A>

// With cancellation — fetch is aborted when the Op is replaced or aborted
const saveProfile = Op.create(
  (signal) => (data: ProfileData) =>
    fetch("/profile", { method: "POST", body: JSON.stringify(data), signal })
      .then(r => {
        if (!r.ok) throw new Error(`${r.status} ${r.statusText}`);
        return r.json() as Promise<ProfileData>;
      }),
  (e) => new ApiError(e),
);

// No input — fetches the current user; manager.run() takes no arguments
const fetchCurrentUser = Op.create(
  (signal) => () => fetch("/me", { signal }).then(r => {
    if (!r.ok) throw new Error(`${r.status} ${r.statusText}`);
    return r.json() as Promise<User>;
  }),
  (e) => new ApiError(e),
);
const manager = Op.interpret(fetchCurrentUser, { strategy: "once" });
manager.run(); // no argument needed