| 1 | export async function* queue(initialize) { |
| 2 | let resolve; |
| 3 | const values = []; |
| 4 | |
| 5 | const dispose = initialize((x) => { |
| 6 | values.push(x); |
| 7 | if (resolve) resolve(values.shift()), (resolve = null); |
| 8 | return x; |
| 9 | }); |
| 10 | |
| 11 | if (dispose != null && typeof dispose !== "function") { |
| 12 | throw new Error( |
| 13 | typeof dispose.then === "function" |
| 14 | ? "async initializers are not supported" |
| 15 | : "initializer returned something, but not a dispose function" |
| 16 | ); |
| 17 | } |
| 18 | |
| 19 | try { |
| 20 | while (true) { |
| 21 | yield values.length ? values.shift() : new Promise((_) => (resolve = _)); |
| 22 | } |
| 23 | } finally { |
| 24 | if (dispose != null) { |
| 25 | dispose(); |
| 26 | } |
| 27 | } |
| 28 | } |