【问题标题】:How can I unroll callbacks in Coffeescript?如何在 Coffeescript 中展开回调?
【发布时间】:2014-09-02 21:05:06
【问题描述】:

通常在 Javascript 中我可以这样做:

var step;
determineStep();

function determineStep() {
    step = 'A';
    asyncCallbackA(function(result)) {
        if (result.testForB) performB();
    });
}

function performB() {
    step = 'B';
    asyncCallbackB(function(result)) {
        if (result.testForC) performC();
    });
}

function performC() {
    step = 'C';
    ...
}

但是 Coffeescript 不允许命名函数被提升,所以我必须在调用它之前定义一个函数。这将导致它们出现故障(非常混乱)。如果它们中的任何一个具有循环依赖关系,则根本不可能。

在 Coffeescript 中我不得不这样做:

step = null
determineStep =
    step = 'A'
    asyncCallbackA (result) ->
      if result.testForB
          step = 'B'
          asyncCallbackB (result) ->
              if result.testForC
                  step = 'C'
                  asyncCallbackC (result) ->
                      ...
determineStep()

如果您有多个步骤,这很快就会失控。

是否可以在 Coffeescript 中实现 Javascript 模式?如果没有,处理这种情况的最佳方法是什么?

【问题讨论】:

    标签: callback coffeescript nested unroll


    【解决方案1】:

    我觉得你有点困惑。当你说:

    f = -> ...
    

    var f(当然)被提升到范围的顶部,但 f = function() { ... } 定义留在原处。这意味着唯一重要的顺序是您需要在 determineStep() 之前定义所有函数。

    例如this works just fine:

    f = -> g()
    g = -> h()
    h = -> console.log('h')
    f()
    

    在你的情况下:

    step = null
    
    determineStep = -> 
        step = 'A'
        asyncCallbackA (result) -> performB() if(result.testForB)
    
    performB = ->
        step = 'B'
        asyncCallbackB (result) -> performC() if(result.testForC)
    
    performC = ->
        step = 'C'
        ...
    
    determineStep()
    

    应该没问题。 determineStep 可以在定义 performB 之前调用 performB(按源顺序),因为:

    1. var performB 被吊起。
    2. determineStep 执行时,performB = function() { ... } 将已完成。

    其他函数也是如此,因此您不必担心函数之间的相互依赖关系。

    【讨论】:

      猜你喜欢
      • 2012-06-13
      • 2013-10-24
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 2012-05-01
      • 2013-06-19
      • 1970-01-01
      • 2014-02-28
      相关资源
      最近更新 更多