A simple Semaphore implementation which provides a limited queue for ensuring proper concurrency.

Param: max

The maximum number of tasks which are allowed concurrently.

Example: Using a Semaphore

// Some async function that takes time to execute
function fn(x) {
return new Promise(resolve => {
setTimeout(() => {
console.log(x);
resolve(x);
}, 1000));
}
};

// Create a Semaphore and add many concurrent tasks
const semaphore = new Semaphore(1);
for ( let i of Array.fromRange(100) ) {
semaphore.add(fn, i);
}

Properties

Accessors

Methods

Properties

max: number

The maximum number of tasks which can be simultaneously attempted.

Accessors

  • get remaining(): number
  • The number of pending tasks remaining in the queue

    Returns number

  • get active(): number
  • The number of actively executing tasks

    Returns number

Methods

  • Add a new tasks to the managed queue

    Parameters

    • fn: Function

      A callable function

    • Optional Rest ...args: any[]

      Function arguments

    Returns Promise<any>

    A promise that resolves once the added function is executed

  • Abandon any tasks which have not yet concluded

    Returns void

  • Private

    Attempt to perform a task from the queue. If all workers are busy, do nothing. If successful, try again.

    Returns any