2012-12-03 66 views
1

我迷失在回调中。代码和期望的输出如下。那么什么发生的是内环不执行应该打印@b阵列=> [“A”,“B”,“C”]Node.js回调|异步forEach嵌套循环与瀑布流

Async = require('async') 

    @a = [1,2,3] 
    @b = ['a','b','c'] 

    Async.forEachSeries @a, (aa , cbLoop1) => 
    console.log aa 
    console.log "^ number from Loop-1" 
    Async.forEachSeries @b, (bb , cbLoop2) => 
     #call the method below 
     Async.waterfall(
      [ 
      (cb) -> 
       #call method 'start' 
       #'start' method has a callback that gets info using HTTP GET 
       start bb , (error , response) -> 
        #console.log(response) or do something with response 
       cbLoop2() 
      ]  
    ) 
    cbLoop1() 


    # Desired OUTPUT 
    1 
^number from Loop-1 
    a 
    b 
    c 
    2 
^number from Loop-1 
    a 
    b 
    c 
    3 
^number from Loop-1 
    a 
    b 
    c  
+0

欢迎来到node.js,其中控制流成为一个挑战。 – usr

回答

0

*大卫答案帮了我。我试图掌握Async forSeries和瀑布语法。欢迎任何需要改进的内容!

Async = require('async') 

class Test 
    constructor:() -> 
    @a1  = [1,2,3] 
    @b1  = ['a','b','c'] 

    test: (t , callback) -> 
    Async.forEachSeries @a1, (aa , cbLoop1) => 
     console.log "Value from Array @a1 - > #{aa}" 
     count = 0 
     Async.forEachSeries @b1, (bb , cbLoop2) => 
    cb = cbLoop2 
    # console.log bb 
    Async.waterfall(
     [ 
     (cbLoop2) -> 
      count = count + 1 
      t.methd1 "Value from Array @b2 - #{bb}" , (er ,response) -> 
      console.log response 
      cbLoop2(null , count) 
     , (resp , cbLoop2) -> 
      #have to do some manupulations here 
      cbLoop2(null , count) 
     ] , (err ,response) -> 
     cbLoop2() 

    ) 

    , (err) -> 
    console.log("===") 
    cbLoop1() 


    methd1: (data , callback) -> 
    @finalmethod "$$ #{data} $$" , callback 

    finalmethod: (data, callback) -> 
    setTimeout() -> 
     callback(undefined , data) 
    , 1500 


    t = new Test() 
    t.test t, t.test_cb 


output 
Value from Array @a1 - > 1 
$$ Value from Array @b2 - a $$ 
$$ Value from Array @b2 - b $$ 
$$ Value from Array @b2 - c $$ 
=== 
Value from Array @a1 - > 2 
$$ Value from Array @b2 - a $$ 
$$ Value from Array @b2 - b $$ 
$$ Value from Array @b2 - c $$ 
=== 
Value from Array @a1 - > 3 
$$ Value from Array @b2 - a $$ 
$$ Value from Array @b2 - b $$ 
$$ Value from Array @b2 - c $$ 
=== 
1

async.waterfall需要一个第二参数:“一种可选的回调来运行一旦所有功能都完成了“。您的问题尚不清楚这是否会影响您尝试实现的流程,但您是否可以拨打cbLoop2()作为waterfall的第二个参数,而不是在第一项任务结束时调用它?一个简单的例子:

async = require('async') 

a = [1,2,3] 
b = ['a','b','c'] 

cb = -> 

async.forEachSeries a, (item , cb) -> 
    console.log item 
    async.forEachSeries b, (item , cb) -> 
    console.log item 
    async.waterfall [], cb() 
    cb() 
+0

非常感谢您的快速响应。这是有帮助的,实际上你是正确的流如果我有async.waterfall之间,这就是我想要做的...瀑布中的所有步骤后,它应该去循环2中的下一个值.. –