Defer - API
A defer function defers the execution of a function until the surrounding function returns.
Installation
- npm
- yarn
- pnpm
npm is the default package manager for Node.js, and to where tscommon is published.
Your project is using npm if it has a
Run the following command in your terminal:
Your project is using npm if it has a
package-lock.json
file in its root folder.Run the following command in your terminal:
terminal
npm install @tscommon/defer
Usage
- Synchronous
- Asynchronous
main.ts
import { DeferFunction } from '@tscommon/defer';
// It is important to use the `using` keyword here.
using defer = new DeferFunction();
console.log('start');
defer(() => console.log('a'));
defer(() => console.log('b'));
console.log('end');
// Output:
// start
// end
// b
// a
main.ts
import { setTimeout } from 'timers/promises';
import { DeferFunction } from '@tscommon/defer';
async function println(message: string): Promise<void> {
await setTimeout(Math.random() * 1000);
console.log(message);
}
async function main(): Promise<void> {
// It is important to use the `using` keyword here.
await using defer = new DeferFunction();
console.log('start');
defer(() => println('a'));
defer(() => println('b'));
console.log('end');
}
main();
// Output:
// start
// end
// b
// a