【问题标题】:Iced coffee script with multiple callbacks带有多个回调的冰咖啡脚本
【发布时间】:2012-05-04 02:26:35
【问题描述】:

当我刷新多个数据源时,我正在使用带有结果 js 的 Iced coffescript。 refresh 方法有两个回调,一个代表成功,一个代表错误,我想等待每个调用都进行回调。

如果不创建附加功能,我看不到如何使用 idced coffescript 执行此操作。我的问题是 - 有没有更优雅的方式可以让我服从多个回调之一?

这是我目前的代码:

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]

【问题讨论】:

    标签: coffeescript iced-coffeescript


    【解决方案1】:

    这也是我发现的唯一方法。我在 Backbone 中使用它并用 @icedSave 包装(例如)模型的 @save 函数:

    # An IcedCoffeescript friendly version of save
    icedSave: (callback) ->
        @save {},
            success: (model, response) -> callback(true, model, response)
            error: (model, response) -> callback(false, model, response)
    

    【讨论】:

    • 我会这样做,尽管也可以(但更复杂)分配一个新的集合点,从该集合点创建两个延迟,然后只等待第一个返回。
    【解决方案2】:

    这是我用来将 Promises .then (-> onSuccess), (-> onError) 转换为 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
    

    您可以稍微修改esc 函数以处理每个回调的多个参数。

    【讨论】:

      【解决方案3】:

      iced.Rendezvous lib 是针对这种情况显式创建的:在多个回调的第一个处返回。来自the docs

      这是一个展示不同输入和输出的示例 一个约会。它执行两个并行的 DNS 查找,并且仅在 第一个返回:

      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]}"
      

      【讨论】:

        猜你喜欢
        • 2014-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-12
        • 1970-01-01
        • 2015-11-06
        • 2014-01-10
        • 1970-01-01
        相关资源
        最近更新 更多