Created
March 19, 2020 14:04
-
-
Save nikostoulas/3133bacc5145a29efba59c8a09d5c5a1 to your computer and use it in GitHub Desktop.
Synchronised block of code in node.js - Example inspired by rabbit-queue implementation of prefetch
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 globalPrefetch = 10; | |
async function changePrefetch(prefetchNum) { | |
await new Promise(r => setTimeout(r, 10)); | |
globalPrefetch = prefetchNum; | |
} | |
async function subscribeToQueue(name, prefetch) { | |
await changePrefetch(prefetch); | |
await new Promise(r => setTimeout(r, 20)); | |
console.log(`subscribing to queue ${name} with prefetch ${globalPrefetch}`); | |
} | |
let lock; | |
async function subscribeToQueueWithLock(name, prefetch) { | |
await lock; | |
lock = changePrefetch(prefetch).then(async () => { | |
await new Promise(r => setTimeout(r, 20)); | |
console.log(`subscribing to queue ${name} with prefetch ${globalPrefetch}`); | |
}); | |
} | |
/** The correct solution is this */ | |
async function subscribeToQueueWithLocalLock(name, prefetch) { | |
let localLock; | |
do { | |
localLock = lock; | |
await lock; | |
} while (localLock !== lock); | |
lock = changePrefetch(prefetch).then(async () => { | |
await new Promise(r => setTimeout(r, 20)); | |
console.log(`subscribing to queue ${name} with prefetch ${globalPrefetch}`); | |
}); | |
} | |
async function subscribeToManyQueues() { | |
subscribeToQueueWithLocalLock('one', 1); | |
subscribeToQueueWithLocalLock('two', 2); | |
subscribeToQueueWithLocalLock('three', 3); | |
} | |
module.exports = subscribeToManyQueues; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment