Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@getify
Last active June 7, 2020 18:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/7ee89ee6f52451bf94110d4fcfbd42f0 to your computer and use it in GitHub Desktop.
Save getify/7ee89ee6f52451bf94110d4fcfbd42f0 to your computer and use it in GitHub Desktop.
native JS async-iterator event stream
async function main() {
var btn = document.getElementById("my-button");
// eventStream here is a native JS async iterator
var eventStream = onEvent(btn)("click");
// this is the key thing: we can use a `for-await..of` loop
// to consume the async-iterator
for await (let evt of eventStream) {
console.log("click!");
}
}
main();
var onEvent = el => evtName => {
var { pr, next } = getDeferred();
el.addEventListener(evtName,handler,false);
return eventStream();
// ******************
async function *eventStream(){
while (true) {
yield pr;
}
}
function handler(evt) {
var f = next;
({ pr, next } = getDeferred());
f(evt);
}
function getDeferred() {
var next;
var pr = new Promise(res => next = res);
return { pr, next };
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment