asynchronous-lock
v2.1.1
Published
Provide many asynchronous locks.
Readme
Asynchronous Lock
This package provides many locks for synchronizing asynchronous processes
Install
pnpm add asynchronous-lockWhy Need Lock
We must know why do we need locks in JavaScript which is a single-threaded language, here is an example
Mock a database that has two asynchronous functions
readandwriteclass Database { private count: number; private constructor() { this.count = 0; } static create(): Database { return new Database(); } async read(): Promise<number> { return this.count; } async write(count: number) { this.count = count; } }Define
increasefunction that can increasecountin databaseasync function increase(database: Database) { const count = await database.read(); await database.write(count + 1); }Test asynchronously
async function test() { const database = Database.create(); await Promise.all([ increase(database), increase(database), increase(database), increase(database), increase(database), ]); const count = await database.read(); console.log(count); // Unexpected result 1 (expect to be 5) }
Asynchronous executions may cause unexpected result, that's why we need locks in JavaScript
Usage
Semaphore: See Semaphore.spec.tsMutex: See Mutex.spec.tsSelector: See Selector.spec.ts
