Skip to content

Instantly share code, notes, and snippets.

@pketh
Last active April 5, 2023 02:12
Show Gist options
  • Save pketh/2d036345483b690d5da020f2903891d7 to your computer and use it in GitHub Desktop.
Save pketh/2d036345483b690d5da020f2903891d7 to your computer and use it in GitHub Desktop.
Promises in Coffeescript
# 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'
# 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
# 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'
Promise.all [myCoolPromise, myOtherCoolPromise].then (arrayOfResults)->
# this part will run after all promises have finished
console.log 'yay my promises finished'
@pketh
Copy link
Author

pketh commented Jun 28, 2016

there are fancier promise things you can do (see http://www.html5rocks.com/en/tutorials/es6/promises/) but the above will get you through 95% of life in a non scary way.

@seza443
Copy link

seza443 commented Mar 15, 2017

Thanks, it helps me 👍

@willdeed
Copy link

willdeed commented Apr 4, 2023

appreciate the examples

@willdeed
Copy link

willdeed commented Apr 5, 2023

for 2-promises-as-function.coffee should line 3 be this instead?: myCoolPromise = (param) ->

It's not clear to me how the param is used

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