Skip to content

Instantly share code, notes, and snippets.

@schleumer
Last active August 29, 2015 14:22
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 schleumer/7162107ad76c5a28f33c to your computer and use it in GitHub Desktop.
Save schleumer/7162107ad76c5a28f33c to your computer and use it in GitHub Desktop.
Why use Promise's constructor instead of Promise.resolve/Promise.reject

Let's declare a function that explicitly throws an error

hehe = ->
  throw new Error "OMFG"

Let's simulate some behavior within Promise's constructor

p = ->
  new Promise (resolve, reject) ->
    resolve hehe!

Let's simulate some behavior without Promise's constructor

p2 = ->
  Promise.resolve hehe!

This one will break application, kill your family and eat your cat. It's because it's not wrapped on Promise's constructor which is like a jail for hungry monsters that want see you wake up 6AM at sunday to fix your application.

p2!
  .then (x) ->
    console.log x
  .catch (e) ->
    console.log e
    
# outputs NO NOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e n​ot rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ

This one will not break the application because it's safe on Promise's constructor jail.

p!
  .then (x) ->
    console.log x
  .catch (e) ->
    console.log e

# outputs [Error: OMFG]

If you are wrapping some library that throws errors like hell then the constructor is way better, since it will reject the operation when an error is thrown outside your application's domain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment