Function latest

Source
latest<TFn extends AnyFn>(
    args: LatestConstructor<TFn>,
): (...args: Parameters<TFn>) => Promise<AwaitRet<TFn>>

An async event wrapper that always resolve to the result of the latest call.

In the example below, both call will return the result of the second call (2)

import { latest } from "@pistonite/pure/sync";

let counter = 0;

const execute = latest({
fn: async () => {
counter++;
await new Promise((resolve) => setTimeout(() => {
resolve(counter);
}, 1000));
}
});

const result1 = execute();
const result2 = execute();
console.log(await result1); // 2
console.log(await result2); // 2

See LatestConstructor options for more advanced usage, for example, control how arguments are updated when new calls are made.