Skip to content

Instantly share code, notes, and snippets.

@michaelsbradleyjr
Last active August 18, 2019 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelsbradleyjr/af2f5282584ac509deee524e3f0d7c78 to your computer and use it in GitHub Desktop.
Save michaelsbradleyjr/af2f5282584ac509deee524e3f0d7c78 to your computer and use it in GitHub Desktop.
/* global setTimeout */
(async () => {
const [iter, send, done] = (() => {
let promise;
let resolve;
const queue = [];
const setPromise = () => {
promise = new Promise(res => { resolve = res; });
};
setPromise();
const send = (v) => {
queue.push(v);
if (queue.length === 1) resolve();
};
const DONE = Symbol('done');
const done = () => { send(DONE); };
const iterator = async function*() {
let v;
while (true) {
if (!queue.length) await promise;
v = queue.shift();
if (v === DONE) break;
if (!queue.length) setPromise();
yield v;
}
};
return [iterator(), send, done];
})();
setTimeout(() => send(1), 1000);
setTimeout(() => send(2), 2000);
setTimeout(() => send(3), 3000);
setTimeout(done, 4000);
setTimeout(() => send(4), 5000); // won't print `x: 4` because it's already done
for await (const x of iter) {
console.log('x:', x);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment