Skip to content

Instantly share code, notes, and snippets.

@thanhpk
Created September 8, 2018 17:23
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 thanhpk/38b57f3ce51b7086f7dfe724cde7f349 to your computer and use it in GitHub Desktop.
Save thanhpk/38b57f3ce51b7086f7dfe724cde7f349 to your computer and use it in GitHub Desktop.
class Channel {
constructor () {
this.csm = []
this.msg = []
}
enqueue (data) {
this.msg.push(data)
this.pass()
}
dequeue () {
return new Promise(resolve => {
let p = { resolve }
this.csm.push(p)
this.pass()
setTimeout(() => {
p.resolve = undefined
resolve([undefined, 'timeout'])
}, 500)
})
}
pass () {
if (this.csm.length == 0 || this.msg.length == 0) return
var cons = this.csm.shift()
/* ignore outdated consumer */
if (!cons.resolve) {
this.pass()
return
}
var mess = this.msg.shift()
cons([mess, undefined])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment