Created
March 15, 2017 20:36
-
-
Save yarax/236a969b4309d77a0c4a2ecd0a22bc7a to your computer and use it in GitHub Desktop.
factorial promises
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 ZeroValue extends Error {} | |
class OtherValue extends Error {} | |
function resolveValue(val) { | |
return Promise.resolve().then(() => { | |
if (!val) throw new ZeroValue(); | |
throw new OtherValue(val); | |
}); | |
} | |
function factorial(n) { | |
return resolveValue(n) | |
.catch(ZeroValue, () => 1) | |
.catch(OtherValue, val => factorial(val.message — 1).then(prev => val.message * prev)) | |
} | |
factorial(4).then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment