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.
Perform side effects on the current function return. Powered by Explicit Resource Management Proposal and using
Declarations and Explicit Resource Management.
npm i defer-function --save
yarn add defer-function
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
// !
});