Created
July 29, 2024 15:03
-
-
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.
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
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