1

使用coffeescript 编码 一种解决方案 | 看到这个帖子

我有两个循环。我想从数组'a'中获取每个值,然后遍历'b'的所有值处理它们并移动到数组'a'中的下一个值

预期输出:

1 a b c
2 a b c
3 a b c

我看到的错误:

 [ 1, 2, 3 ]

 [ 'a', 'b', 'c' ]

 1
 2
 3

 TypeError: Cannot read property 'length' of undefined
   at Object.forEachSeries(~/src/node_modules/async/lib/async.js:103:17)




  Async = require('async')

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

  console.dir @a
  console.dir @b

  Async.forEachSeries @a, (aa , cbLoop1) ->
    console.log aa
    cbLoop1()
    Async.forEachSeries @b, (bb , cbLoop2) ->
      #here will be some callback that I need to process before moving to next value in
      #b array
      console.log bb
      cbLoop2()
4

1 回答 1

2

您的第一个Async.forEachSeries电话需要一个回调,这会改变this

Async.forEachSeries @a, (aa , cbLoop1) ->
  # inside the callback, the value of `this` has changed,
  # so @b is undefined!

使用=>语法将 的值保留this在回调内部:

Async.forEachSeries @a, (aa , cbLoop1) =>
  console.log aa
  cbLoop1()
  Async.forEachSeries @b, (bb , cbLoop2) ->
    # use `=>` again for this callback if you need to access this (@) inside
    # this callback as well
于 2012-12-02T00:28:47.450 回答