Skip to content

Instantly share code, notes, and snippets.

@victor141516
Created July 29, 2024 15:03
Show Gist options
  • Save victor141516/36906cb6db1cc40623e3fff9fd630273 to your computer and use it in GitHub Desktop.
Save victor141516/36906cb6db1cc40623e3fff9fd630273 to your computer and use it in GitHub Desktop.
This is like a promise you can that resets itself. Acts as a queue.
type GateKeeper = {
wait: () => Promise<void>
pass: () => void
}
const createGateKeeper = (): GateKeeper => {
let resolver!: () => void
let promise!: Promise<void>
const reset = () => {
promise = new Promise<void>((res) => {
resolver = res
})
}
reset()
const queue = (async function* iife() {
while (true) {
// eslint-disable-next-line no-await-in-loop
await promise
reset()
yield
}
})()
return {
wait: () => queue.next().then(noop),
pass: () => resolver(),
}
}
const gateKeeper = createGateKeeper()
const f1 = async () => {
await gateKeeper.wait()
console.log('My turn!')
}
const f2 = () => {
gateKeeper.pass()
console.log('I\'m passing!')
}
f1()
f2()
/**
* I'm passing!
* My turn!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment