Last active
August 7, 2019 15:45
-
-
Save TerrorJack/a20a4512b31356e9c9a115bef08525d7 to your computer and use it in GitHub Desktop.
Async JavaScript Channels
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
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