Skip to content

lock

The lock function ensures that an asynchronous function is not executed simultaneously, allowing calls to be queued or rejected according to configuration.

Syntax

typescript
lock(callback, options?)

Parameters

NameTypeDescription
callbackFunctionAsynchronous function to be protected by the lock.
optionsobject(Optional) Settings: { queue, onLocked, onError }.

options object

NameTypeDescription
queuebooleanIf true, calls during the lock are queued (default: true).
onLockedFunctionFunction called when a call is blocked.
onErrorFunctionFunction called in case of an error during callback execution.

Return Value

TypeDescription
FunctionAsynchronous function that respects the lock and the configured options.

Examples

typescript
const lockedFn = lock(async () => {
  await sleep(100);
  console.log('Executed!');
});

lockedFn();
lockedFn(); // Executes in sequence, not simultaneously

Notes

  • Throws an error if the callback is not a function.
  • Useful for avoiding race conditions in asynchronous operations.

References

Released under the MIT License.