diff --git a/src/lib/utils/parallelAction.ts b/src/lib/utils/parallelAction.ts new file mode 100644 index 0000000..d704630 --- /dev/null +++ b/src/lib/utils/parallelAction.ts @@ -0,0 +1,46 @@ +/** + * Parallel Server Action utilities. + * + * Server Actions are dispatched sequentially per client in Next.js. + * `createParallelAction` wraps a server function so its outer wrapper + * returns immediately without awaiting the inner work, freeing the + * dispatch queue. The real work continues asynchronously on the server, + * and the result is streamed back via React Flight. + * + * Usage: + * + * // server (in a "use server" file): + * export const getData = createParallelAction(async (id: string) => { + * return await fetchExpensiveData(id); + * }); + * + * // client: + * const result = await runParallelAction(getData("abc")); + * + * Multiple calls can run in parallel — each outer Action returns instantly, + * so the Next.js serial queue does not block subsequent calls. + * + * @see https://github.com/icflorescu/next-server-actions-parallel + */ + +/** + * Wrap an async server function so it returns immediately without awaiting + * the inner work. The outer function completes instantly (returning a + * Flight-wrapped promise tuple), so the Next.js Server Action dispatch + * queue is freed for the next call. + */ +export function createParallelAction( + action: (...args: U) => Promise, +) { + return async (...args: U) => [action(...args)] as const; +} + +/** + * Await the result of a parallel Server Action created by + * {@link createParallelAction}. Call this on the client side. + */ +export async function runParallelAction( + result: Promise]>, +) { + return (await result)[0]; +}