Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save night-fury-rider/1bda4fafedfb36db87ff1cf3cb913d64 to your computer and use it in GitHub Desktop.
Save night-fury-rider/1bda4fafedfb36db87ff1cf3cb913d64 to your computer and use it in GitHub Desktop.
Design Pattern - Async Iterator
class MyAsyncIterator {
constructor() {
this.queue = []; // To hold actual values
this.waitlist = []; // To hold the callbacks
}
/**
* If the waitlist contains an item, remove it and execute it.
* Otherwise, add the value to the queue.
*/
push(val) {
if (this.waitlist.length > 0) {
const firstCallback = this.waitlist.shift();
firstCallback(val);
} else {
this.queue.push(val);
}
}
/**
* If the queue has an item, remove it and execute it with RESOLVE.
* Otherwise, add the callback to the waitlist.
*/
next() {
// Since it's gonna need a promise, we will return a Promise.
return new Promise((resolve) => {
// Something is in queue, remove that value
if (this.queue.length > 0) {
const firstValue = this.queue.shift();
resolve(firstValue);
} else {
// Queue is empty, hence add callback to waitlist
this.waitlist.push(resolve);
}
});
}
}
function start() {
const iterator = new MyAsyncIterator();
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