Skip to content

Instantly share code, notes, and snippets.

@sitepodmatt
Last active August 12, 2017 07:26
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 sitepodmatt/4e89a8d456e71c49ada22be8c72948ca to your computer and use it in GitHub Desktop.
Save sitepodmatt/4e89a8d456e71c49ada22be8c72948ca to your computer and use it in GitHub Desktop.
playing with async
class K8SInformer {
constructor() {
this.listeners = [];
this.queue = [];
}
addListener(listener) {
this.listeners.push(listener);
}
async hold() {
return new Promise((f, j) => {
if(this.queue.length > 0) {
setTimeout(f, 0);
} else {
this.awake = f;
}
});
}
addItems(items) {
this.queue.push(...items);
if(this.awake) {
this.awake();
this.awake = null;
}
}
async start() {
while (true) {
while(true) {
const item = this.queue.splice(0,1)[0];
if(!item) break;
let itemPromises = [];
for (let listener of this.listeners) {
itemPromises.push(listener.queue(item));
}
await Promise.all(itemPromises);
}
console.log('holding');
await this.hold();
console.log('released');
}
}
}
function simulateProcessorDelay() {
return new Promise((f,j) => setTimeout(f, Math.random() * 100));
}
// test
var informer = new K8SInformer();
informer.addListener({
queue: async function(item) {
await simulateProcessorDelay();
console.log(`item: ${JSON.stringify(item)}`);
}
});
informer.start()
informer.addItems([
{ name: 'matt' },
{ name: 'fred' },
{ name: 'smith' }
]);
setTimeout(() => {
informer.addItems([{ name: 'Mr late' }]);
}, 2000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment