Skip to content

Instantly share code, notes, and snippets.

@developerfromjokela
Created November 21, 2020 15:10
Show Gist options
  • Save developerfromjokela/aea273bdee9d5817d39ddaa101013255 to your computer and use it in GitHub Desktop.
Save developerfromjokela/aea273bdee9d5817d39ddaa101013255 to your computer and use it in GitHub Desktop.
Async iterator for node js
class AsyncIterator {
constructor(callback, endCallback, items) {
this.currentItem = -1;
this.items = items;
this._callback = callback;
this._endCallback = endCallback;
}
set callback(value) {
this._callback = value;
}
nextItem() {
if (this.currentItem+1 < this.items.length) {
this.currentItem++;
this._callback(this.items[this.currentItem]);
} else {
this._endCallback()
}
}
set endCallback(value) {
this._endCallback = value;
}
}
module.exports = {
AsyncIterator: AsyncIterator
}
@developerfromjokela
Copy link
Author

Leave callback undefined, and define it after creating class, and do same to endCallback if you want.

When you've defined all callbacks, call nextItem() to start iteration. From your callback, to proceed to next item, call same function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment