Created
November 21, 2020 15:10
-
-
Save developerfromjokela/aea273bdee9d5817d39ddaa101013255 to your computer and use it in GitHub Desktop.
Async iterator for node js
This file contains hidden or 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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Leave callback
undefined
, and define it after creating class, and do same toendCallback
if you want.When you've defined all callbacks, call
nextItem()
to start iteration. From yourcallback
, to proceed to next item, call same function.