Created
November 15, 2017 17:50
-
-
Save dotproto/e8a6b88ddf988ecec22a5cfe8440b9a3 to your computer and use it in GitHub Desktop.
An async iteration experiment. I was thinking about RxJS-like observables.
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
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