Skip to content

A defer function defers the execution of a function until the surrounding function returns

Notifications You must be signed in to change notification settings

igrek8/defer-function

Repository files navigation

Defer Function

Edit defer-function

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 and using Declarations and Explicit Resource Management.

Installation

npm i defer-function --save
yarn add defer-function

Usage

import getDeferFunction from "defer-function";

function main() {
  using defer = getDeferFunction();
  defer(() => console.log("world"));
  console.log("hello");
}

main();

console.log("!");

// Output:
// hello
// world
// !
import getDeferFunction from "defer-function";

async function print(message: string) {
  return new Promise<void>((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
  // !
});

About

A defer function defers the execution of a function until the surrounding function returns

Topics

Resources

Stars

Watchers

Forks