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.
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();
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
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 do:
npm install one-time-execution-method
BSD-2-Clause