-
-
Save Raynos/1626aca4c5940888576e to your computer and use it in GitHub Desktop.
This file contains 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
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