Skip to content

Instantly share code, notes, and snippets.

@mariusGundersen
Last active November 9, 2015 21:39
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 mariusGundersen/bfeb7d8da2d019f5df17 to your computer and use it in GitHub Desktop.
Save mariusGundersen/bfeb7d8da2d019f5df17 to your computer and use it in GitHub Desktop.
AsyncQueue example
export default class AsyncQueue {
constructor() {
this.items = [];
this.receivers = [];
}
push(value) {
if(this.receivers.length == 0){
this.items.push(value);
}else{
this.receivers.shift()(value);
}
}
pop() {
return new Promise(resolve =>
this.items.length == 0
? this.receivers.push(resolve)
: resolve(this.items.shift()));
}
}
const queue = new AsyncQueue();
async function producer(queue){
let x = 0;
while(true){
await delay(Math.random()*1000);
queue.push(x++)
}
}
async function consumer(queue){
while(true){
await delay(Math.random()*250);
console.log(await queue.pop());
}
}
producer(queue);
consumer(queue);
consumer(queue);
consumer(queue);
consumer(queue);
function delay(time){
return new Promise(r => setTimeout(r, time));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment