Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created May 28, 2013 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Raynos/1626aca4c5940888576e to your computer and use it in GitHub Desktop.
Save Raynos/1626aca4c5940888576e to your computer and use it in GitHub Desktop.
module.exports = { Promise: Promise, map: map, chain: chain, either: either, cache: cache }
// minimal promises.js
function map(promise, lambda) {
return Promise(function (resolve, reject) {
promise.then(function (x) { resolve(lambda(x)) }, reject)
})
}
function chain(promise, lambda) {
return Promise(function (resolve, reject) {
promise.then(function (value) {
lambda(value).then(resolve, reject)
}, reject)
})
}
function either(promise, recover, lambda) {
return Promise(function (resolve, reject) {
promise.then(function (value) {
lambda ? lambda(value).then(resolve, reject) : resolve(value)
}, function (error) {
recover(error).then(resolve, reject)
})
})
}
function cache(promise) {
var cached, resolves, rejects
return Promise(function (resolve, reject) {
if (cached) {
return (cached.v ? resolve(cached.v) : reject(cached.e))
} else if (resolves) {
return resolves.push(resolve), rejects.push(reject)
}
resolves = [resolve], rejects = [reject]
promise.then(function (value) {
cached = { v: value } && resolves.forEach(function (r) { r(value) })
}, function (error) {
cached = { e: error } && rejects.forEach(function (r) { r(error) })
})
})
}
function Promise(handler) {
return { then: function (f, r) { handler(f, r) } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment