【问题标题】:How can I use await/defer to handle passing success and error callbacks?如何使用 await/defer 处理传递的成功和错误回调?
【发布时间】:2014-06-28 15:11:58
【问题描述】:

比如下面的代码:

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

然后调用函数

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

如果我要传递多个回调,但都不能保证会被调用,我该如何为这种情况构建 await/defer?还是我需要完全重新考虑我的代码,只提供一个回调,然后评估其中是否存在错误?

【问题讨论】:

    标签: iced-coffeescript


    【解决方案1】:

    你可以调用一个中间函数,比如从他们两个中完成,然后在 await/defer 块中调用这个新的包装函数。

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

    【讨论】:

    • 为您的答案提供更多详细信息。不仅仅是链接
    【解决方案2】:

    Iced CoffeeScript 需要一个单独的回调作为延续。在某些情况下,像以前那样使用回调会更有意义。

    • 如果一个回调总是被调用一次,合并它们并使用await。

    • 如果回调可能被调用零次或多次,请不要使用await——而是传递回调函数。

    例如,Node.js 的异步 filesystem API 非常适合 await,因为您需要它在继续之前返回一个值:

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

    …但是一个 HTTP 服务器,它的回调可能被多次调用,必须是一个普通的回调:

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

    在您的情况下,如果您打算使用 Iced CoffeeScript,则重组更有意义,以便您的方法采用单个回调。

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 2017-08-09
      • 2021-12-31
      • 2020-06-11
      • 2018-09-03
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多