Last active
April 22, 2020 03:16
-
-
Save creationix/590fe6e3f3e511b41217be0aa2a77692 to your computer and use it in GitHub Desktop.
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
const locks = {}; | |
async function protect(fn, name, ...args) { | |
while (locks[name]) await locks[name] | |
return (locks[name] = new Promise(async (resolve) => { | |
const ret = await fn(name, ...args); | |
delete locks[name]; | |
resolve(ret); | |
})); | |
} | |
////////////////////////////////////////////////////////// | |
async function unsafeWork(key) { | |
// Simulate doing work | |
console.log(key, "Start"); | |
await new Promise(resolve => setTimeout(resolve, 100)); | |
console.log(key, "End"); | |
return `Returned from ${key}`; | |
} | |
function safeWork(key) { | |
return protect(unsafeWork, key); | |
} | |
safeWork(1).then(console.log); | |
safeWork(2).then(console.log); | |
safeWork(1).then(console.log); | |
safeWork(2).then(console.log); | |
safeWork(3).then(console.log); | |
safeWork(3).then(console.log); | |
safeWork(1).then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you call
unsafeWork
directly, it looks like:But with
safeWork
, you never have concurrent calls on the same key: