使用CoffeeScript的Step.js和异步控制流程

时间:2012-11-13 19:32:22

标签: node.js asynchronous coffeescript

我正在尝试使用coffee-script使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)

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

2 个答案:

答案 0 :(得分:2)

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
)

答案 1 :(得分:0)

想出来。因此,由于coffee具有隐式返回语句,因此它将返回最后一个语句(或表达式,如果你愿意)的值。步骤库假定当您从正在执行同步步进的函数返回显式值时(使得更容易混合和匹配同步和异步操作)。这在Javascript中非常有用,我们有明确的return语句。

解决方法是始终返回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)
相关问题