Last active
September 17, 2020 23:08
-
-
Save forrest-akin/0b95ea0a100c956bcc93133eb18ec090 to your computer and use it in GitHub Desktop.
demonstrating a use case for condition variables in JavaScript
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 asyncMeaningOfLife = () => | |
Promise.resolve({ meaningOfLife: 42 }) | |
const updateResult = result => update => | |
Object.assign(result, update, { processing: false }) | |
function syncFun(afterUpdate) { | |
const result = { processing: true } | |
asyncMeaningOfLife() | |
.then(updateResult(result)) | |
.then(afterUpdate) | |
return result | |
} | |
function CondVar() { | |
let signal | |
const waitPromise = new Promise(resolve => { signal = resolve }) | |
return { signal | |
, wait: () => waitPromise | |
} | |
} | |
describe(`syncFun`, () => { | |
it('should eventually produce the meaning of life', async () => { | |
const condVar = CondVar() | |
const result = syncFun(condVar.signal) | |
expect(result.processing).toBe(true) | |
await condVar.wait() | |
expect(result.processing).toBe(false) | |
expect(result.meaningOfLife).toBe(42) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment