簡體   English   中英

Node.js回調| 異步forEach嵌套循環與瀑布流

[英]Node.js Callbacks | Async forEach nested loop with waterfall flow

我迷失在回調中。 代碼和所需的輸出如下。 因此,發生的情況是未執行應打印@b array => ['a','b','c']的內部循環

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    

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()

*大衛的回答幫助了我。 我正在嘗試掌握Async forSeries和Waterfall語法。 *歡迎任何改進意見!

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 $$
===

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM