Skip to content

Instantly share code, notes, and snippets.

@hax
Created May 13, 2020 15:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hax/9cf04a4e090c5bab1d658b72c996f82b to your computer and use it in GitHub Desktop.
Save hax/9cf04a4e090c5bab1d658b72c996f82b to your computer and use it in GitHub Desktop.
A experimental Channel in JS
// kotlin channel: https://kotlinlang.org/docs/reference/coroutines/channels.html
// golang channel
class Channel {
constructor() {
this._s = null
this._r = null
}
send(v) {
if (this._r) {
this._r(v)
this._r = null
return
} else {
if (this._s) throw new Error()
return new Promise(r => this._s = [r, v] )
}
}
receive() {
if (this._s) {
const [r, v] = this._s
this._s = null
r()
return v
} else {
if (this._r) throw new Error()
return new Promise(r => this._r = r)
}
}
async *[Symbol.asyncIterator]() {
for (;;) yield this.receive()
}
}
const ch = new Channel()
void async function() {
for await (const x of ch) console.log(x)
}()
setInterval(() => {
ch.send((Math.random() * 100) | 0)
}, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment