Last active
August 18, 2019 14:34
-
-
Save michaelsbradleyjr/af2f5282584ac509deee524e3f0d7c78 to your computer and use it in GitHub Desktop.
This file contains 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
/* 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