I put my code on code review stack exchange a couple of years back and got this AsyncLock implementation suggested to me which is much less code. Due to it being from stackexchange the code above is licensed (CC-BY-SA 3.0) with attributiton given to blindman67
P.S. this only works in really modern browsers that support async iterables. Like Chrome 63 (at this point in time Chrome Canary is version 63.)
I saw a comment on Hacker News that said it would be nice to have a lock on variables for async because two things using the same resource can cause problems. Semaphores work for things with more than one resource (you can use a AsyncQueue to do the semaphore pattern. Semaphores and the AsyncQueue are explained in kriskowals GTOR).
My implementation uses the fact that JS is single-threaded so this implementation is likely not thread-safe.
To create a lock I just used the semaphore pattern with only one resource. I subclassed AsyncQueue
to add a length variable for the length of available resources in AsyncQueueLength
which in AsyncLock
I created an AsyncQueue and enforced that it only have one resource max.
The main file is test.js which uses the async lock in AsyncLock.js
which uses gtor.js
for the AsyncQueue
.
Here's the block if you want to check the console output without downloading it. https://bl.ocks.org/johnsonjo4531/99256568deaf8c0f1685793a4a8205bb