Locko
Locko is a small package for locking critical sections of code.
When to use
Use locko when you need to ensure that only one "thread" can be inside of a section of code at once. Consider the following code.
{ return { ; };} { console; await ; console; await ; console;} ;;;
Without locko, this will print:
First
First
First
Second
Second
Second
Third
Third
Third
Now add locko:
const locko = ; { return { ; };} { await locko; console; await ; console; await ; console; locko;} ;;;
This will now print:
First
Second
Third
First
Second
Third
First
Second
Third
A real world example
It's often the case that you need to both read and write to a file, but without any kind of synchronization strategy, it's possible to read from a file while it's being written, or write to a file while it's being read, or have more than one writer writing at once. This is very likely to cause failures in an application.
Using locko you can ensure that no more than one operation is being executed on a file at any given time.
{ await locko; return { fs; }; } { await locko; return { fs; };}
Best practices
If you never unlock the lock, it will remain locked forever. Therefore you should usually use a try-catch to ensure that the lock gets released. For example:
{ try await locko; console; await ; console; await ; console; locko; catch err locko; throw err; }