Skip to content

Instantly share code, notes, and snippets.

@yarax
Created March 15, 2017 20:36
Show Gist options
  • Save yarax/236a969b4309d77a0c4a2ecd0a22bc7a to your computer and use it in GitHub Desktop.
Save yarax/236a969b4309d77a0c4a2ecd0a22bc7a to your computer and use it in GitHub Desktop.
factorial promises
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.message1).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