2

For instance take the following code:

getThing = (thing_id, cb_success, cb_error)  ->
  model.findById thing_id, 
    (error, thing) ->
      if error || !thing 
        cb_error "error" 
      else
        cb_success thing

And then to call the function

getThing thing_id
, (thing) ->
  console.log "Found a thing!"
, (error) 
  console.log" Uh oh..."

If I'm passing multiple callbacks, none of which are guaranteed to be called, how can I structure await/defer for this case? Or do I need to totally rethink my code to only provide a single callback and then evaluate the presence of an error within that?

DanH
  • 5,498
  • 4
  • 49
  • 72

2 Answers2

0

You can call an intermediary function, like finish from both of them, and then call this new wrapper function in the await/defer block.

https://gist.github.com/maxtaco/2683cbc3379a95b6703f

0

Iced CoffeeScript expects a single callback that it uses as a continuation. In some cases it makes more sense to use callbacks like you're used to.

  • If one callback will always be called one time, merge them and use await.

  • If a callback might be called zero or more than one time, don't use await — pass a callback function instead.

For example, Node.js's async filesystem API is a great candidate for await, since you need it to return a value before you continue:

await fs.stat somePath, defer(err, stats)

…but an HTTP server, whose callback may be called more than once, must be a normal callback:

http.createServer (req, res) ->
   # handle the request

In your case, if you're going to used Iced CoffeeScript it makes more sense to restructure so that your methods take a single callback.

s4y
  • 50,525
  • 12
  • 70
  • 98