Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Async Iterator Example
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);
}
};
}
@artisonian

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment