【问题标题】:Step.js and Asynchronous Control Flow with CoffeeScriptStep.js 和 CoffeeScript 的异步控制流
【发布时间】:2012-11-02 06:38:06
【问题描述】:

我正在尝试让 Step.js 库与咖啡脚本一起正常工作。我对咖啡很陌生,但这是我的尝试:

setTimeout(
  =>
    console.log("step 1 at #{new Date}")
    setTimeout(
      =>
        console.log("step 2 at #{new Date}")
        setTimeout(
          =>
            console.log("step 3 at #{new Date}")
          10000
        )
      10000
    )
  10000
)

# step 1 at Tue Nov 13 2012 13:18:51 GMT-0600 (CST)
# step 2 at Tue Nov 13 2012 13:19:01 GMT-0600 (CST)
# step 3 at Tue Nov 13 2012 13:19:11 GMT-0600 (CST)

应该与:

step(
  ->
    setTimeout(
      =>
        console.log("step 1 at #{new Date}")
        this(null)
      10000
    )
  ->
    setTimeout(
      =>
        console.log("step 2 at #{new Date}")
        this(null)
      10000
    )
  ->
    setTimeout(
      =>
        console.log("step 3 at #{new Date}")
        this(null)
      10000
    )
)

# step 1 at Tue Nov 13 2012 13:12:04 GMT-0600 (CST)
# step 2 at Tue Nov 13 2012 13:12:04 GMT-0600 (CST)
# step 3 at Tue Nov 13 2012 13:12:04 GMT-0600 (CST)

从上面的示例步骤中可以看出,步骤是同时执行所有步骤,而不是像预期的那样一次执行一个步骤。我不太清楚为什么会是现在。

【问题讨论】:

    标签: node.js asynchronous coffeescript


    【解决方案1】:

    CoffeeScript 在函数的最后一个表达式前隐式添加return。这是 Step 的一个问题,它假定如果您返回任何内容,则该步骤是同步的。

    解决方案是在每个步进函数的末尾添加一个显式的return

    step(
      ->
        setTimeout(
          =>
            console.log("step 1 at #{new Date}")
            this(null)
          10000
        )
        return
      ->
        setTimeout(
          =>
            console.log("step 2 at #{new Date}")
            this(null)
          10000
        )
        return
      ->
        setTimeout(
          =>
            console.log("step 3 at #{new Date}")
            this(null)
          10000
        )
        return
    )
    

    【讨论】:

    • 谢谢你打败我;)。我喜欢你的回报,没有未定义的价值,它更干净。我会把它标记为答案
    【解决方案2】:

    想通了。因此,由于咖啡具有隐式返回语句,它将返回最后一条语句的值(或表达式,如果你愿意的话)。 Step 库假定当您从函数返回显式值时,您正在执行同步步进(使其更容易混合和匹配同步和异步操作)。这在 Javascript 中效果很好,我们有明确的返回语句。

    解决方法是始终返回 undefined:

    step(
      ->
        setTimeout(
          =>
            console.log("step 1 at #{new Date}")
            this(null)
          10000
        )
        return undefined
      ->
        setTimeout(
          =>
            console.log("step 2 at #{new Date}")
            this(null)
          10000
        )
        return undefined
      ->
        setTimeout(
          =>
            console.log("step 3 at #{new Date}")
            this(null)
          10000
        )
        return undefined
    )
    
    # step 1 at Tue Nov 13 2012 13:38:51 GMT-0600 (CST)
    # step 2 at Tue Nov 13 2012 13:39:01 GMT-0600 (CST)
    # step 3 at Tue Nov 13 2012 13:39:11 GMT-0600 (CST)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      相关资源
      最近更新 更多