Skip to content

Instantly share code, notes, and snippets.

@BYK
Created May 20, 2021 08:02
Show Gist options
  • Save BYK/e49f45530127af433e9f91f5c5269992 to your computer and use it in GitHub Desktop.
Save BYK/e49f45530127af433e9f91f5c5269992 to your computer and use it in GitHub Desktop.
A simple async mutex implementation
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