Skip to content

Instantly share code, notes, and snippets.

@JonWatkins
Last active April 11, 2016 16:14
Show Gist options
  • Select an option

  • Save JonWatkins/76bd6b8eabb23d2fee7075e27eeb0aff to your computer and use it in GitHub Desktop.

Select an option

Save JonWatkins/76bd6b8eabb23d2fee7075e27eeb0aff to your computer and use it in GitHub Desktop.
Simple iterator using promises
(function (a) {
'use strict'
class Iterator {
constructor() {
this.tasks = []
this.result = {}
}
addTask(name, fn) {
this.tasks.push(new Promise((resolve, reject) => {
if (typeof name === 'function') {
fn = name
name = fn.name
}
if (fn.length === 0) {
resolve({ name: name, value: fn() })
}
else {
fn((err, res) => {
if (err) return reject(err)
resolve({ name: name, value: res })
})
}
}))
}
setRes(res, next) {
this.result[res.name] = res.value
next()
}
run () {
return new Promise((resolve, reject) => {
let it = this.tasks[Symbol.iterator]()
let next = () => {
let item = it.next()
if (item.done) return resolve(this.result)
item.value
.then(res => this.setRes(res, next))
.catch(err => reject(err))
}
next()
})
}
}
a.Iterator = Iterator
})(window)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment