Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iced coffee script with multiple callbacks

I'm using Iced coffescript with upshot js when I am refreshing multiple data sources. The refresh method has TWo call backs one for success and one for error and I want to wait for each call to make either callback.

I can't see how to do this with idced coffescript without making an additional function. My question is - is there a more elegant way that I can defer to one of multiple callbacks?

This is the code I have currently:

refreshMe = (key, value, result) =>
    value.refresh(
    (success)=>
            result success
    ,
    (fail, reason, error)=>
        result undefined, fail
    )
@refresh = () =>                
success={}
fail={}
await
    for key, value of @dataSources
    refreshMe key, value, defer success[key], fail[key]
like image 557
Giles Bradshaw Avatar asked Apr 23 '12 13:04

Giles Bradshaw


2 Answers

This is the only way I have found to do it too. I'm using it in Backbone and wrap (for example) a model's @save function with an @icedSave:

# An IcedCoffeescript friendly version of save
icedSave: (callback) ->
    @save {},
        success: (model, response) -> callback(true, model, response)
        error: (model, response) -> callback(false, model, response)
like image 132
devdave Avatar answered Nov 17 '22 22:11

devdave


Here's some code I use for converting Promises .then (-> onSuccess), (-> onError) to errbacks (err, result) ->:

# You can write like this:
await value.refresh esc defer e, result


# onError - function to be called when promise rejected.
# onSuccess - function to be called when promise is fulfilled.
module.exports = esc = (onError, onSuccess) ->
  util = require 'util'
  return (result) ->
    if util.isError result
      # Always send back an error to first handler.
      onError? result
    else if onSuccess?
      console.log onSuccess, result
      # `await fn esc done, defer result`
      onSuccess? result
    else
      # `await fn esc done`
      onError? null, result

You could modify the esc function a bit to handle multiple arguments for each callback.

like image 31
vaughan Avatar answered Nov 17 '22 22:11

vaughan