Last active
March 1, 2019 00:08
-
-
Save artisonian/cbeaa8730e2ad9a017d0b7ff24f443d8 to your computer and use it in GitHub Desktop.
Async Iterator Example
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
main().catch(console.error); | |
async function main() { | |
const clicks = streamify(document, "click"); | |
let clickCount = 0; | |
for await (const event of clicks) { | |
console.log("click", event, clickCount); | |
if (clickCount++ > 2) { | |
clicks.return(); | |
} | |
} | |
console.log("bye"); | |
} | |
function streamify(element, event) { | |
const pushQueue = []; | |
const pullQueue = []; | |
let done = false; | |
function pushValue(event) { | |
if (pullQueue.length !== 0) { | |
pullQueue.shift()({ value: event, done: false }); | |
} else { | |
pushQueue.push(event); | |
} | |
} | |
function pullValue() { | |
return new Promise(resolve => { | |
if (pushQueue.length !== 0) { | |
resolve({ value: pushQueue.shift(), done: false }); | |
} else { | |
pullQueue.push(resolve); | |
} | |
}); | |
} | |
element.addEventListener(event, pushValue); | |
return { | |
[Symbol.asyncIterator]() { | |
return this; | |
}, | |
next() { | |
return done ? this.return() : pullValue(); | |
}, | |
return() { | |
done = true; | |
element.removeEventListener(event, pushValue); | |
return Promise.resolve({ value: undefined, done }); | |
}, | |
throw(error) { | |
done = true; | |
return Promise.reject(error); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See Understand Async Iterators Without Really Trying and event-emitter-to-async-iterator.js.