function cache
cache<T>(
key: string | string[],
value: () => T | Promise<T>,
options?: { timeout?: number; },
): Promise<T>

Fetch and cache expensive computations using Deno KV.

Caches the result of an async function call. If the cached value exists and hasn't expired, returns it immediately. Otherwise, calls the function, caches the result, and returns it.

Use cases:

  • Cache expensive API calls
  • Store computed results between runs
  • Reduce redundant processing
  • Implement time-based invalidation

Examples

Cache API results

import { cache, HOURS } from "jsr:@j50n/proc";

const data = await cache(
  "api-data",
  async () => {
    // Expensive operation
    const response = await fetch("https://api.example.com/data");
    return await response.json();
  },
  { timeout: 4 * HOURS }
);

Cache with array key

import { cache } from "jsr:@j50n/proc";

const result = await cache(
  ["user", userId, "profile"],
  async () => await fetchUserProfile(userId),
  { timeout: 30 * 60 * 1000 } // 30 minutes
);

Type Parameters

Parameters

key: string | string[]

Cache key (string or array of strings).

value: () => T | Promise<T>

Function to compute the value if not cached.

optional
options: { timeout?: number; }

Timeout in milliseconds (default: 24 hours).

Return Type

Promise<T>

The cached or computed value.