Synchronized - API
In an async environment, a race condition occurs when two or more async operations attempt to update mutable shared data at the same time. @synchronized decorator offers a mechanism to avoid race conditions by synchronizing async operations access to shared data.
Installation
- npm
- yarn
- pnpm
npm is the default package manager for Node.js, and to where tscommon is published.
Your project is using npm if it has a
Run the following command in your terminal:
Your project is using npm if it has a
package-lock.json
file in its root folder.Run the following command in your terminal:
terminal
npm install @tscommon/synchronized
Usage
Enable decorators:
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true
}
}
main.ts
import { setTimeout } from 'timers/promises';
import { synchronized } from '@tscommon/synchronized';
class SynchronizedObject {
@synchronized // Executes the method serially
public async execute(value: number): Promise<void> {
await setTimeout(Math.random() * 1000);
console.log(value);
}
}
const obj = new SynchronizedObject();
obj.execute(1);
obj.execute(2);
obj.execute(3);
// 1
// 2
// 3