Skip to content

Instantly share code, notes, and snippets.

@vojtatranta
Last active January 18, 2017 21:16
Show Gist options
  • Save vojtatranta/ca7a53e2be0d7802831dbbf2fda7a182 to your computer and use it in GitHub Desktop.
Save vojtatranta/ca7a53e2be0d7802831dbbf2fda7a182 to your computer and use it in GitHub Desktop.
function asyncIter(arr, fn, errCb) {
var i = 0
function runIt() {
try {
fn(arr[i], i, function() {
i++
if (i < arr.length) {
setTimeout(runIt, 5)
}
})
} catch (err) {
return errCb(err)
}
}
if (arr.length > 0) {
setTimeout(runIt, 5)
}
}
function Promise (fn) {
this._thens = []
this._catch = null
this._completed = false
try {
fn(this._resolve.bind(this), this._reject.bind(this))
} catch (err) {
this._reject(err)
}
}
Promise.prototype._resolve = function(result) {
setTimeout(function() {
this._result = result
this._completed = true
this._complete(result)
}.bind(this), 5)
}
Promise.prototype._reject = function(err) {
setTimeout(function() {
this._complete(undefined, err)
}.bind(this))
}
Promise.prototype.then = function(fn) {
if (this._completed) {
this._callThens()
} else {
this._thens.push(fn)
}
return this
}
Promise.prototype.catch = function(fn) {
this._catch = fn
return this
}
Promise.prototype._callThens = function() {
var result = this._result
asyncIter(this._thens, function(thenCb, i, next) {
var prom = thenCb(result)
if (prom instanceof Promise) {
prom.then(function(res) {
result = res
next()
})
if (this._catch) {
prom.catch(this._catch.bind(this))
}
} else {
result = prom
next()
}
}.bind(this), function(err) {
this._reject(err)
}.bind(this))
}
Promise.prototype._complete = function(result, error) {
if (result) {
try {
this._callThens()
} catch (err) {
if (this._catch) {
this._catch(err)
} else {
throw new Error('Uncaugt Promise rejection!')
}
}
} else if (error && this._catch) {
this._catch(error)
}
}
var prom = new Promise(function(resolve, reject) {
console.log('bem')
resolve('ahoj')
})
prom.then(function(res) {
console.log('heh')
return new Promise(function(resolve) {
resolve('cau')
})
})
.then(function(result) {
console.log('cau?', result)
return result
})
//.then(function(res) {
// throw new Error('erooor')
//})
.catch(function(err) {
console.log('bubu', err)
})
console.log('bum')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment