Add parallel server action utilities
This commit is contained in:
parent
a4686c09b5
commit
77b7db9dd1
46
src/lib/utils/parallelAction.ts
Normal file
46
src/lib/utils/parallelAction.ts
Normal file
@ -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<T, U extends unknown[]>(
|
||||||
|
action: (...args: U) => Promise<T>,
|
||||||
|
) {
|
||||||
|
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<T>(
|
||||||
|
result: Promise<readonly [Promise<T>]>,
|
||||||
|
) {
|
||||||
|
return (await result)[0];
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user