Last active
November 9, 2015 21:39
-
-
Save mariusGundersen/bfeb7d8da2d019f5df17 to your computer and use it in GitHub Desktop.
AsyncQueue example
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
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())); | |
} | |
} |
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
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