1.0.15 • Published 4 years ago
@eu-ge-ne/lock-async v1.0.15
@eu-ge-ne/lock-async
Dead simple async lock. Written in TypeScript. With exponential backoff
Install | Example | API | License
Install
$ npm install @eu-ge-ne/lock-async
Example
Swap 2 values in async functions concurrently:
import { LockAsync } from "@eu-ge-ne/lock-async";
const lock = new LockAsync();
const wait = () => new Promise(resolve => setTimeout(resolve, 10));
let a = 1;
let b = 2;
const first = lock.run(async () => {
await wait();
const c = a;
await wait();
a = b;
await wait();
b = c;
});
const second = lock.run(async () => {
await wait();
const c = a;
await wait();
a = b;
await wait();
b = c;
});
await Promise.all([first, second]);
API
Create instance
Constructor parameters:
timeout: number // default = 3000
base: number // default = 1
ceiling: number // default = 10
import { LockAsync } from "@eu-ge-ne/lock-async";
const lock1 = new LockAsync(3000, 1, 10);
// or
const lock2 = new LockAsync();
Run async function
import assert from "assert";
const result = await lock.run(() => new Promise(resolve => setTimeout(() => resolve("Result"), 100)));
assert.strict.equal(result, "Result");
Get status
const { locked, waiters, maxLockWaitTime } = lock.status();
locked: boolean
- lock statewaiters: number
- number of lock waitersmaxWaiters: number
- max waiters during lock lifetimemaxLockWaitTime: number
- max time, lock spent waitingmaxLockAttempts: number
- max attempts, made during single lock