如何在coffeescript的for循环中使用async系列?

时间:2015-08-11 19:32:14

标签: javascript coffeescript async.js

我在coffeescript中使用caolan的async lib。我的任务在for循环中,在循环完全执行后,我需要运行回调函数。

这就是我现在所拥有的。我不希望最终的回调在for循环中每次运行。我怎么能这样做?

 for key, value of settings
  async.series([
    ((callback) ->
      getSetting key, (value) ->
        #do something and create object settingValues
      callback(null, settingValues)
    )
  ],
  #final callback which I want to run after the entire for loop is completed.  
  (err, results) ->
    someFunction results
  )

1 个答案:

答案 0 :(得分:0)

如果你真的想用async.series for循环来构造一个函数数组,那么传递数组

 arr = []

 for key, value of settings
   arr.push (callback) ->
     getSetting key, (value) -> 
       callback(null, settingValues)


 async.series arr, (err, results) -> someFunction results

或者,您可以使用异步来迭代

async.map Object.keys(settings), (key, callback) ->
    # if you need 'value' in here, use settings[key]
    getSetting key, (value) ->
      callback(null, settingValues)
, (err, results) -> someFunction results