Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save night-fury-rider/1bda4fafedfb36db87ff1cf3cb913d64 to your computer and use it in GitHub Desktop.

Select an option

Save night-fury-rider/1bda4fafedfb36db87ff1cf3cb913d64 to your computer and use it in GitHub Desktop.
Design Pattern - Async Queue
class AsyncQueue {
constructor() {
this.values = []; // To hold actual values
this.callbacks = []; // To hold the callbacks
}
/**
* If the callbacks array has something, remove it and execute it.
* Otherwise, add the value to the values array.
*/
push(val) {
if (this.callbacks.length > 0) {
let firstCallback = this.callbacks.shift();
return firstCallback(val);
} else {
this.values.push(val);
}
}
/**
* If the values array has something, remove it and execute it with RESOLVE.
* Otherwise, add the callback to the callbacks array.
*/
next() {
// Since it's gonna need a promise, we will return a Promise.
return new Promise((resolve) => {
// Something is in values, remove that value
if (this.values.length > 0) {
let firstValue = this.values.shift();
return resolve(firstValue);
} else {
// Values array is empty, hence add callback to callbacks array
this.callbacks.push(resolve);
}
});
}
}
function start() {
const iterator = new AsyncQueue();
iterator.push(1);
iterator.push(2);
iterator.next().then((val) => {
console.log(val);
}); // 1
iterator.next().then((val) => {
console.log(val);
}); // 2
iterator.next().then((val) => {
console.log(val);
}); // console 3 after 2000 milliseconds.
setTimeout(() => {
iterator.push(3);
}, 2000);
}
start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment