Skip to content

Instantly share code, notes, and snippets.

@m-allanson
Created July 25, 2022 12:17
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 m-allanson/7c88da0895ec269f29386098b448b31b to your computer and use it in GitHub Desktop.
Save m-allanson/7c88da0895ec269f29386098b448b31b to your computer and use it in GitHub Desktop.
class Queue {
constructor(private items: number[] = []) {}
async count() {
return this.items.length;
}
async pop() {
return this.items.shift();
}
async push() {
const randomInt = Math.floor(Math.random() * (1000 - 1))
return this.items.push(randomInt);
}
}
const wait = function() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('waited');
resolve(undefined);
});
});
}
class Runner {
constructor(private queue: Queue) {}
async *asyncItemIterator(queue: Queue) {
while (await queue.count() > 0) {
await wait();
yield queue.pop();
}
}
async process() {
const processNextItem = this.asyncItemIterator(this.queue);
setTimeout(() => {console.log('Log second')});
console.log('Log first')
for await (const item of processNextItem) {
console.log(`Nonblocking item: ${item}`);
}
}
}
const queueItems = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const queueInstance = new Queue(queueItems);
const runner = new Runner(queueInstance);
runner.process();
@m-allanson
Copy link
Author

m-allanson commented Jul 25, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment