Skip to content

Instantly share code, notes, and snippets.

@baruchiro
Last active January 6, 2021 07:39
Show Gist options
  • Save baruchiro/96a9cfc9376a20f7420d8b59cb38eafb to your computer and use it in GitHub Desktop.
Save baruchiro/96a9cfc9376a20f7420d8b59cb38eafb to your computer and use it in GitHub Desktop.
Three ways to mutual exclusion in NodeJS
const wait = (s: number) => new Promise((resolve) => setTimeout(resolve, s * 1000))
let promRef
const download = async () => {
if (promRef) return promRef
promRef = wait(3).then(() => {
console.log('finished')
promRef = null
return 'resolved'
})
return promRef
}
setInterval(() => download().then((r) => console.log(`${r} interval 1`)), 1 * 1000)
setInterval(() => download().then((r) => console.log(`${r} interval 2`)), 1 * 1000)
setInterval(() => download().then((r) => console.log(`${r} interval 3`)), 1 * 1000)
/*
Output:
[LOG]: "finished"
[LOG]: "resolved interval 1"
[LOG]: "resolved interval 2"
[LOG]: "resolved interval 3"
[LOG]: "resolved interval 1"
[LOG]: "resolved interval 2"
[LOG]: "resolved interval 3"
[LOG]: "resolved interval 1"
[LOG]: "resolved interval 2"
[LOG]: "resolved interval 3"
[LOG]: "resolved interval 1"
[LOG]: "resolved interval 2"
[LOG]: "resolved interval 3"
Playground Link:https://www.typescriptlang.org/play?#code/MYewdgzgLgBA7gQwJawLwwBQQFwzAVwFsAjAUwCcBKGVAPj1LhgAVyRCkJSMNzSIQAGwBupanRhcoAFSSFSIfFF78hogDSSYAKhgBGAAxHKlALAAoC4NKwADm0IAlUgDMLF0JFgATEHDCCIAjeNDAIEACeYMCY4vQA3hYwyTBILpj27M4u1HxQ+ORgMJlOru7mKcUO2aGIKBgAzJQAdFAAFqRgPHEwiRWVKZ4C1s2BAOYYAOQuSGCcHd6TZv0DVVmuoQSCgkmrMHkFRZN8w6KLu8kAvsuVB4VrpW7ml+VSAJJgUBTCCILdNPRfP5AsEMC12p0eFQATAhkJSKMQBMAAYAEni5EuqU+31++mRJk0eh0+iMBmW7xx5B+fzBMKBASC3jBrQ6XV4PThI3GGDRGKxsy+1LxACYCZQiSTDMYLJShTT-hIGSDmeC2VDOeBhgieXzMdj5XiGuLJbppeSLEA
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment