Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An async iteration experiment. I was thinking about RxJS-like observables.
function clickPromise(el) {
// Create pointers for proimse chain methods
let _resolve = null
let _reject = null
const p = new Promise((resolve, reject) => {
// Cache the promise chain methods for future use
_resolve = resolve
_reject = reject
})
// Subscribe to the next click & pass the event object down the promise chain
el.addEventListener('click', _resolve, {once: true})
return p;
}
// // Test that binding a single click event works as expected
// clickPromise().then(msg => console.log(msg));
async function* clickStream(el) {
let proceed = true;
while (proceed) {
proceed = yield clickPromise(el);
}
}
async function asyncWhile(generator, continueCheck, mapFn) {
const iterator = generator();
let value = null;
let response;
while (value = await continueCheck(val => iterator.next(val))) {
mapFn(value.value);
}
}
let i = 0;
asyncWhile(
() => clickStream(document.body),
iterator => iterator(++i < 3),
msg => console.log(msg)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.