Last active
January 2, 2016 18:29
-
-
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.
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
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