-
-
Save getify/7ee89ee6f52451bf94110d4fcfbd42f0 to your computer and use it in GitHub Desktop.
native JS async-iterator event stream
This file contains hidden or 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
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(); |
This file contains hidden or 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
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