@ayonli/jsext
Version:
A JavaScript extension package for building strong and modern applications.
33 lines (32 loc) • 1.16 kB
TypeScript
/**
* Inspired by Golang, creates a function that receives a `defer` keyword which
* can be used to carry deferred jobs.
* @module
*/
/**
* Inspired by Golang, creates a function that receives a `defer` keyword which
* can be used to carry deferred jobs that will be run after the main function
* is complete.
*
* Multiple calls of the `defer` keyword is supported, and the callbacks are
* called in the LIFO order. Callbacks can be async functions if the main
* function is an async function or an async generator function, and all the
* running procedures will be awaited.
*
* @example
* ```ts
* import func from "@ayonli/jsext/func";
* import * as fs from "node:fs/promises";
*
* export const getVersion = func(async (defer) => {
* const file = await fs.open("./package.json", "r");
* defer(() => file.close());
*
* const content = await file.readFile("utf8");
* const pkg = JSON.parse(content);
*
* return pkg.version as string;
* });
* ```
*/
export default function func<T, R = any, A extends any[] = any[]>(fn: (this: T, defer: (cb: () => void) => void, ...args: A) => R): (this: T, ...args: A) => R;