【问题标题】:how to handle implicit return in coffeescript when using async.js使用async.js时如何处理coffeescript中的隐式返回
【发布时间】:2013-11-10 21:49:49
【问题描述】:

我正在努力

testFunction: () ->
  console.log "testFunction"
  async.series(
    (->
      console.log "first"
    ),
    (-> 
      console.log "second"
    )
  )

我也试过没有成功

testFunction: () ->
  console.log "testFunction"
  async.series(
    (->
      console.log "first"
      return undefined
    ),
    (-> 
      console.log "second"
      return undefined
    )
  )

要运行,我希望控制台输出“testFunction”、“first”、“second”,但我得到的是“testFunction”、“second”,并且咖啡脚本使用隐式返回似乎存在问题, (我猜)。

附件是从上述coffeescript编译的javascript输出的屏幕截图。

【问题讨论】:

    标签: coffeescript async.js


    【解决方案1】:

    为异步工作的每个函数都需要将回调作为其唯一参数。

    one = (callback) ->
      console.log "one"
      callback()
    
    two = (callback) ->
      console.log "two"
      callback()
    
    testFunction: () ->
      console.log "testFunction"
      async.series [one, two], (error) ->
        console.log "all done", error
    

    【讨论】:

    • 这是一个非常有用的答案,谢谢。这就是我感到沮丧的地方,现在已经查看了一些文档,但并不清楚我是否需​​要达到这一点。如果不能传入参数,如何在闭包参数中给出函数?
    • 所以故事有点复杂,但我想保持简单。从技术上讲,您可以使用 async.apply 并接受多个参数,但最后一个始终是告诉 async “我完成了”的回调。
    【解决方案2】:

    你有很多问题。首先是您没有将正确的参数传递给async.series。它期望:

    async.series([functions...], callback)
    

    当你打电话时

    async.series(function, function)
    

    由于第一个函数的length 属性未定义,它假定它是一个空数组并直接跳到“回调”(第二个函数)。听起来您可能想要传递一个包含两个函数的数组并省略回调。

    第二个问题是传递给async.series 的函数必须调用回调才能继续进行。回调是每个函数的第一个参数:

    testFunction: () ->
      console.log "testFunction"
      async.series([
        ((next) ->
          console.log "first"
          next()
        ),
        ((next) -> 
          console.log "second"
          next()
        )
      ])
    

    async 忽略您传递给它的大多数(全部?)函数的返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-21
      • 2015-05-18
      • 2016-05-25
      • 2016-06-30
      • 2011-09-18
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多