Skip to content

Instantly share code, notes, and snippets.

@TerrorJack
Last active August 7, 2019 15:45
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 TerrorJack/a20a4512b31356e9c9a115bef08525d7 to your computer and use it in GitHub Desktop.
Save TerrorJack/a20a4512b31356e9c9a115bef08525d7 to your computer and use it in GitHub Desktop.
Async JavaScript Channels
function newThunk(f) {
let t = () => {
const r = f();
t = () => r;
return r;
};
return () => t();
}
function newNode() {
let r,
p = new Promise(resolve => {
r = resolve;
});
return { promise: p, resolve: r, next: newThunk(newNode) };
}
export class Channel {
constructor() {
this.takeNode = newNode();
this.putNode = this.takeNode;
Object.seal(this);
}
take() {
const r = this.takeNode.promise;
this.takeNode = this.takeNode.next();
return r;
}
put(r) {
this.putNode.resolve(r);
this.putNode = this.putNode.next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment