Skip to content

Instantly share code, notes, and snippets.

@forrest-akin
Last active September 17, 2020 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forrest-akin/0b95ea0a100c956bcc93133eb18ec090 to your computer and use it in GitHub Desktop.
Save forrest-akin/0b95ea0a100c956bcc93133eb18ec090 to your computer and use it in GitHub Desktop.
demonstrating a use case for condition variables in JavaScript
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