Last active
August 12, 2017 07:26
-
-
Save sitepodmatt/4e89a8d456e71c49ada22be8c72948ca to your computer and use it in GitHub Desktop.
playing with async
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
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