Created
May 20, 2021 08:02
-
-
Save BYK/e49f45530127af433e9f91f5c5269992 to your computer and use it in GitHub Desktop.
A simple async mutex implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let locks = []; | |
const fn = async () => { | |
let resolve; | |
locks.push(new Promise(r => (resolve=r))); | |
let lock; | |
while (locks.length > 1 && (lock = locks.shift())) | |
await lock; | |
console.log(new Date()); | |
setTimeout(resolve, 1000); | |
} | |
Promise.all((Array.from(Array(10), fn))).then(() => console.log('Done.')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment