Last active
January 16, 2024 10:42
-
-
Save alenaksu/147a7d94bf16865b650f8ff25b85425a to your computer and use it in GitHub Desktop.
Async Generator Queue
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
import { createQueue } from './queue.js'; | |
const fakeAsyncCall = (i: number) => | |
new Promise<void>((resolve) => | |
setTimeout(() => { | |
console.log(i); | |
resolve(); | |
}, 1000) | |
); | |
const queue = createQueue(2); | |
console.log('start'); | |
for (let i = 0; i < 10; i++) { | |
queue.next(() => fakeAsyncCall(i)); | |
} | |
// drain | |
await queue.next(); | |
console.log('end'); |
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
export function createQueue(size: number = Infinity) { | |
const queue: Set<Promise<void>> = new Set(); | |
const queueGenerator = (async function*(): AsyncGenerator<void> { | |
while (true) { | |
if (queue.size >= size) { | |
await Promise.any(queue); | |
} | |
const item = (yield) as () => Promise<void>; | |
if (item) { | |
const promise = Promise.resolve(item()).finally(function () { | |
queue.delete(promise); | |
}); | |
queue.add(promise); | |
} else { | |
await Promise.all(queue); | |
} | |
} | |
})(); | |
queueGenerator.next(); | |
return queueGenerator; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment