Created
April 29, 2020 12:47
-
-
Save gabssnake/1bfab639e4d04dc70450dfce6af7128c to your computer and use it in GitHub Desktop.
Using callbacks as iterators à la React Hooks
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
// Not my credit, this comes from @jedschmidt on Twitter | |
// https://twitter.com/jedschmidt | |
// Example usage: | |
// | |
// void async function() { | |
// let [clicks, onclick] = iterator() | |
// document.querySelector('button').addEventListener('click', onclick) | |
// for await (let click of clicks) console.log(click) | |
// }() | |
export default function iterator() { | |
let done = false | |
let events = [] | |
let resolve | |
let promise | |
defer() | |
return [read(), write, end] | |
function defer() { | |
promise = new Promise(r => resolve = r) | |
} | |
async function* read() { | |
await promise | |
yield* events.splice(0) | |
if (!done) yield* read() | |
} | |
function write(event) { | |
events.push(event) | |
resolve() | |
defer() | |
} | |
function end() { | |
done = true | |
resolve() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment