Question

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]
Était-ce utile?

La solution

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)

Autres conseils

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.

iced.Rendezvous lib is made explicitly for this case: return at the first of multiple callbacks. From the docs:

Here is an example that shows off the different inputs and outputs of a Rendezvous. It does two parallel DNS lookups, and reports only when the first returns:

hosts = [ "okcupid.com", "google.com" ];
ips = errs = []
rv = new iced.Rendezvous
for h,i in hosts
    dns.resolve hosts[i], rv.id(i).defer errs[i], ips[i]

await rv.wait defer which
console.log "#{hosts[which]}  -> #{ips[which]}"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top