-
-
Save mmplisskin/e9a08a2f7d90575dfb709379ae8f0465 to your computer and use it in GitHub Desktop.
Promises in Coffeescript
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
# Create a promise: | |
myCoolPromise = new Promise (resolve, reject) -> | |
# do a thing | |
success = true | |
if success | |
resolve 'stuff worked' | |
else | |
reject Error 'it broke' | |
# Use the promise: | |
myCoolPromise.then (result) -> | |
console.log result # returns 'stuff worked' | |
.catch (error) -> | |
console.log error # returns error: 'it broke' | |
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
# You can also define a promise as a function: | |
myCoolPromise = () -> | |
return new Promise (resolve, reject) -> | |
# do a thing | |
success = true | |
if success | |
resolve 'stuff worked' | |
else | |
reject Error 'it broke' | |
# Use the promise: | |
myCoolPromise(param).then (response) -> | |
console.log 'success', response | |
.catch (error) -> | |
console.error 'failed', error | |
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
# You can also chain thens in a promise: | |
## (handy for running a bunch of async things in sequence) | |
myCoolPromise.then (result) -> | |
console.log result # returns 'stuff worked' | |
return 'abc' | |
.then (response) -> | |
console.log response # returns 'abc' | |
.catch (error) -> | |
console.error error | |
asyncRecovery() # asyncRecovery error handler can have it's own promise chain | |
.then () | |
console.log 'all done' | |
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.all [myCoolPromise, myOtherCoolPromise].then (arrayOfResults)-> | |
# this part will run after all promises have finished | |
console.log 'yay my promises finished' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment