Options
All
  • Public
  • Public/Protected
  • All
Menu

A non-reentrant critical section offering execution of (async) functions therein.

Effectively, it is a wrapper around ISemaphore, also accommodating easy-to-miss edge cases when errors are thrown or Promises rejected.

example

Simple usage:

await criticalSection.do(() => {
  // We acquired the (internal) lock
  // Do something exclusively
});
example

Exceptions in a synchronous exclusive function:

try {
  await criticalSection.do(() => {
    // Errors thrown within the critical section *do* release it again
    throw new Error('oops');
  });
}
catch (err) {
  // Here we will receive the error
  console.log(err);
}
example

Rejections in an asynchronous exclusive function:

try {
  await criticalSection.do(async () => {
    // A returned rejected promise returned within the critical section
    // *does* release it again
    return Promise.reject('oops');

    // `await Promise.reject('oops');` would have the same effect
  });
}
catch (err) {
  // Here we will receive the error
  console.log(err);
}

Hierarchy

  • ICriticalSection

Implemented by

Index

Methods

Methods

do

  • do<T>(func: () => T | Promise<T>): Promise<T>
  • Wait for the critical section to become available and execute a function.

    throws

    The returned promise will be rejected iff. the executed function has thrown an error or has returned a rejecting promise itself.

    Type parameters

    • T

    Parameters

    • func: () => T | Promise<T>

      A function which will be executed exclusively in the critical section.

        • (): T | Promise<T>
        • Returns T | Promise<T>

    Returns Promise<T>

    A promise which is resolved with the (eventually) returned value by func. Effectively, once the critical section has been entered, Promise.resolve(func()) is returned. Especially if func returns a Thenable, by the semantics of Promise.resolve, this Thenable is adopted as the new Promise.
    In other words, it is impossible to make criticalSection.do(...) resolve to a Promise, i.e. await criticalSection.do(...) be a Promise.

Generated using TypeDoc