Skip to content

Instantly share code, notes, and snippets.

@vensder
Forked from pketh/1-promises.coffee
Created November 21, 2020 07:53
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 vensder/06d31f8fedf929b33c44dd3bcbc3542c to your computer and use it in GitHub Desktop.
Save vensder/06d31f8fedf929b33c44dd3bcbc3542c 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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment