Skip to content

Instantly share code, notes, and snippets.

Last active January 21, 2021 01:56
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jed/f8444ae8e6e40e08a7b29944840ac20d to your computer and use it in GitHub Desktop.
Turning callbacks into async iterators, with a React hook-like API.
// 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
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) {
function end() {
done = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment