Skip to content

Instantly share code, notes, and snippets.

@mgutz
Last active January 2, 2016 18:29
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 mgutz/8343496 to your computer and use it in GitHub Desktop.
Save mgutz/8343496 to your computer and use it in GitHub Desktop.
The beauty of promises is they are values. Async and sync calls are handles the same within a `then` statement. In this example, async, sync and error handling are handled gracefully.
Promise = require('bluebird')
i = 0
printAsync = (cb) ->
setTimeout ->
console.log i++
cb()
, Math.floor((Math.random()*10)+1) # random 1..10
print = (action) ->
switch action
when "error"
throw new Error("No more 'return cb() if cb' everywhere. Exceptions handle gracefully")
when "asyncnum"
vow = Promise.pending()
printAsync vow.callback
vow.promise
else
console.log action
Promise
.try(print, "red")
.then ->
print "asyncnum"
.then ->
print "white"
.then ->
print "blue"
.then ->
print "asyncnum"
.then ->
print "error"
.then ->
print "never reached because of error"
.catch (e) ->
console.log e.stack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment