Last active
September 13, 2016 02:40
-
-
Save stevekane/b1aee05239275faaa5eef66f4b4a3a2b to your computer and use it in GitHub Desktop.
Example of a async-oriented monadic main function for javascript
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
async function raf<T> (f: (t: T) => Promise<T>, t: T): Promise<T> { | |
return new Promise(res => requestAnimationFrame(_ => res(f(t)))) as Promise<T> | |
} | |
async function forever<T> (f: (t: T) => Promise<T>, t: T): Promise<T> { | |
return await f(t).then(t1 => forever(f, t1)) | |
} | |
async function update (state: T): Promise<T> { | |
// Your update logic here | |
// Your render logic here | |
return Promise.resolve(state) | |
} | |
async function main (state: T): Promise<T> { | |
// Your functions, async or otherwise here | |
return forever(raf.bind(null, update), state) | |
} | |
main(initialState) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please note, as of the initial publication of this gist, you must target es6 with typescript in order to have native support for Promse, arrow functions and async functions.