one-time-execution-method
v3.1.1
Published
define a method that will be executed only once
Downloads
2,076
Maintainers
Readme
one-time-execution-method
Define methods that will be executed only once.
For async functions the resulting Promise of the 1st. invocation will be preserved and always delivered in the future.
example
import { replaceWithOneTimeExecutionMethod } from "one-time-execution-method";
class MyClass {
constructor() {
this.executions = 0;
}
initialize() {
this.executions++;
return new Promise(resolve => setTimeout(resolve, 1000));
}
}
// replace initialize() method of MyClass to be executed only once
replaceWithOneTimeExecutionMethod(MyClass.prototype, "initialize");
async doit() {
const object = new MyClass();
// start several initializations in parallel
Promise.all([object.initialize(), object.initialize(), object.initialize()]);
await object.initialize();
// even after several parallel executions only one run is done
console.log(this.executions); // -> 1
}
doit();
API
Table of Contents
replaceWithOneTimeExecutionMethod
Replace a given method with one that will only be executed once. For async functions the resulting Promise of the 1st. invocation will be preserved and always delivered in the future.
class MyClass {
async initialize() {
// code here will be executed only once
}
}
replaceWithOneTimeExecutionMethod(MyClass.prototype, "initialize");
const object = new MyClass();
object.initialize(); // body will/can be executed only once
object.initialize(); // 2nd. call immediatly returns
Parameters
transitionState
Object symbol slot holding the state of the method.
- undefined -> call func and store Promise
- Promise -> func currently running or fullfilled -> deliver this Promise
install
With npm do:
npm install one-time-execution-method
license
BSD-2-Clause