Skip to content

Instantly share code, notes, and snippets.

@stevekane
Last active September 13, 2016 02:40
Show Gist options
  • Save stevekane/b1aee05239275faaa5eef66f4b4a3a2b to your computer and use it in GitHub Desktop.
Save stevekane/b1aee05239275faaa5eef66f4b4a3a2b to your computer and use it in GitHub Desktop.
Example of a async-oriented monadic main function for javascript
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)
@stevekane
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment