2

例如采取以下代码:

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?或者我是否需要完全重新考虑我的代码以仅提供一个回调,然后评估其中是否存在错误?

4

2 回答 2

0

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

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

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

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

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

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

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

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

于 2014-10-18T22:24:23.223 回答
0

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

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

于 2014-07-22T02:15:28.733 回答