https://github.com/igrek8/defer-function
A defer function defers the execution of a function until the surrounding function returns
https://github.com/igrek8/defer-function
defer function
Last synced: about 1 year ago
JSON representation
A defer function defers the execution of a function until the surrounding function returns
- Host: GitHub
- URL: https://github.com/igrek8/defer-function
- Owner: igrek8
- Created: 2024-09-15T12:13:36.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-09-16T09:21:07.000Z (almost 2 years ago)
- Last Synced: 2025-01-30T15:20:04.053Z (over 1 year ago)
- Topics: defer, function
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/defer-function
- Size: 6.84 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Defer Function
[](https://codesandbox.io/p/sandbox/m6ffy3)
A defer function defers the execution of a function until the surrounding function returns.
The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
## Motivation
Perform side effects on the current function return. Powered by [Explicit Resource Management Proposal](https://github.com/tc39/proposal-explicit-resource-management) and [`using`
Declarations and Explicit Resource Management](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html).
## Installation
```
npm i defer-function --save
```
```
yarn add defer-function
```
## Usage
```ts
import getDeferFunction from "defer-function";
function main() {
using defer = getDeferFunction();
defer(() => console.log("world"));
console.log("hello");
}
main();
console.log("!");
// Output:
// hello
// world
// !
```
```ts
import getDeferFunction from "defer-function";
async function print(message: string) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(message);
resolve();
});
});
}
async function main() {
await using defer = getDeferFunction();
defer(print, "world");
console.log("hello");
}
main().then(() => {
console.log("!");
// Output:
// hello
// world
// !
});
```