one-time-execution-method
Version:
define a method that will be executed only once
107 lines (74 loc) • 4.01 kB
Markdown
[](https://www.npmjs.com/package/one-time-execution-method)
[](https://spdx.org/licenses/0BSD.html)
[](https://typescriptlang.org)
[](https://bundlejs.com/?q=one-time-execution-method)
[](https://npmjs.org/package/one-time-execution-method)
[](https://github.com/arlac77/one-time-execution-method/issues)
[](https://actions-badge.atrox.dev/arlac77/one-time-execution-method/goto)
[](https://github.com/prettier/prettier)
[](http://commitizen.github.io/cz-cli/)
[](https://snyk.io/test/github/arlac77/one-time-execution-method)
[](https://coveralls.io/github/arlac77/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.
<!-- skip-example -->
```javascript
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();
```
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
* [replaceWithOneTimeExecutionMethod](
* [Parameters](
* [transitionState](
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.
```js
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
```
* `object` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** prototype to bind method against
* `name` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** of the method
Object symbol slot holding the state of the method.
* undefined -> call func and store Promise
* Promise -> func currently running or fullfilled -> deliver this Promise
With [npm](http://npmjs.org) do:
```shell
npm install one-time-execution-method
```
BSD-2-Clause