coffee-script icon indicating copy to clipboard operation
coffee-script copied to clipboard

How can I use await/defer to handle passing success and error callbacks?

Open carn1x opened this issue 11 years ago • 2 comments

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?

carn1x avatar May 24 '14 11:05 carn1x

I would write a converter function to convert it to a one-callback convection.

converter = (cb) ->
   cb_success = (args...) -> cb null, args...
   cb_error = (err) -> cb err
   return [cb_error, cb_success]

await getThing thing_id, converter(defer(err,res))...
console.log err
console.log res

maxtaco avatar May 24 '14 13:05 maxtaco

For reference, I've also used iced.Rendezvous for similar situations. However, it may be overkill for a simple case.

doublerebel avatar Feb 04 '15 17:02 doublerebel