asyncify
asyncify converts a synchronous function into an async function that returns a CancellableHandle. Useful for integrating sync code into async pipelines.
Best for sync-to-async bridging Use
asyncifywhen you need to use a synchronous function in a context that expects a cancellable async function.
Import
Section titled “Import”Root package:
import { asyncify } from "@vgerbot/async";Module subpath:
import { asyncify } from "@vgerbot/async/utils";Leaf subpath:
import { asyncify } from "@vgerbot/async/utils/asyncify";Quick example
Section titled “Quick example”import { asyncify } from "@vgerbot/async";
const syncFn = (x: number, y: number) => x + y;const asyncFn = asyncify(syncFn);
const handle = asyncFn(3, 4);const result = await handle.promise; // 7When to use asyncify
Section titled “When to use asyncify”- Sync-to-async bridging: Convert a sync function for use in async pipelines.
- Library integration: Wrap sync library functions for use with
@vgerbot/asyncAPIs. - Testing: Mock async functions from sync implementations.
- Uniform interfaces: Make all functions in a pipeline return
CancellableHandle.
function asyncify<T, Args extends unknown[] = unknown[]>( fn: (...args: Args) => T, options?: CancellableOptions<T>,): (...args: Args) => CancellableHandle<T>;Parameters
Section titled “Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
fn |
(...args: Args) => T |
— | Synchronous function to wrap. |
options |
CancellableOptions<T> |
undefined |
Cancellable configuration options. |
Return value
Section titled “Return value”Returns a function that takes the same arguments as fn and returns a CancellableHandle<T>.
Execution model
Section titled “Execution model”The returned function wraps fn in a cancellable call. The sync function is executed inside an async wrapper, so any thrown errors become promise rejections.
const parseJson = asyncify(JSON.parse);
try { await parseJson("{ invalid json }").promise;} catch (error) { console.log("Parse error:", error); // SyntaxError}Cancellation
Section titled “Cancellation”Since the wrapped function is synchronous, cancellation only matters if the handle is cancelled before the microtask runs. The CancellableOptions are passed through to the underlying cancellable call.
const asyncRead = asyncify(readFileSync, { name: "fileRead",});
const handle = asyncRead("data.txt");handle.cancel("No longer needed");TypeScript tips
Section titled “TypeScript tips”asyncify preserves the argument types of the original function. The return type becomes CancellableHandle<T>.
const fn = (x: number, y: string): boolean => x > y.length;const asyncFn = asyncify(fn);
const handle = asyncFn(5, "hello"); // CancellableHandle<boolean>const result = await handle.promise; // booleanRelated APIs
Section titled “Related APIs”cancellable— the primitive used byasyncify.constant— returns a constant value as aCancellableHandle.compose— composes async functions.once— executes a function only once.