/one-time-execution-method

define a method that will be executed only once

Primary LanguageJavaScriptBSD 2-Clause "Simplified" LicenseBSD-2-Clause

npm License Typed with TypeScript bundlejs downloads GitHub Issues Build Status Styled with prettier Commitizen friendly Known Vulnerabilities Coverage Status

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

  • object Object prototype to bind method against
  • name string of the method

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