Skip to content

Instantly share code, notes, and snippets.

@maxtaco
Last active December 17, 2015 12:28
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 maxtaco/5609503 to your computer and use it in GitHub Desktop.
Save maxtaco/5609503 to your computer and use it in GitHub Desktop.
A library that simplifies short-circuiting errors in IcedCoffeeScript. Works with ICS 1.6.2c+. Thanks to @ashtuchkin.
# This is a pretty generic short-circuiter class that makes it
# convenient to error out of an iced function on the first error
# to occur.
#
# It assumes that every callback is of the form (err, otherstuff...)
# More general classes are possible using the same technique though.
#
class ErrorShortCircuiter
constructor : (@cb) ->
error_out : (err) ->
if @cb?
tmp = @cb
@cb = null
tmp err
defer : (arg) ->
normal_cb = arg.context._defer arg
(err, everything_else...) =>
if err? then @error_out err
else normal_cb everything_else...
#====================================================================
#
# Test code for the above. You need iced-coffee-script 1.6.2c or higher
# to get this to work...
#
f = (err, i, cb) ->
await setTimeout defer(), 500 + i
cb err, i+1, i+2, i+3
main = (cb) ->
esc = new ErrorShortCircuiter cb
d = { v: [] }
await
f null, 1, esc.defer d.a, d.b, d.c
f null, 10, esc.defer d.v[0], d.v[1]
console.log "phew, everything worked #{JSON.stringify d}"
await
f "shit, bad news!", 20, esc.defer d.j, d.i
f "other bad news -- but this error is lost", 30, esc.defer()
f null, 300, esc.defer x
console.log "we shouldn't get here!"
cb null
await main defer err
console.log "got back err: #{err}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment