【问题标题】:Using async.js to Perform Asynchronous Actions In Loop使用 async.js 在循环中执行异步操作
【发布时间】:2013-06-09 03:05:37
【问题描述】:

我知道我要发布这个然后让它工作,更不用说标题但是......

我的情况是,我需要对给定数组中的每个元素执行一些异步代码,然后在所有元素都完成后进行一些检查。通常,如果我在这里使用 async.js,但是我这样做的方式并没有得到我想要的结果。

所以这是我的逻辑,我想我可以创建一个函数数组,但是我这样做的方式似乎让 async.js 在结果中返回了一个函数列表。

findLeadThatCanBeTaken : (leads, user, manualTake, cb) =>
  if(leads.length == 0) then return cb(null, null)

  funcArr = []
  self = this

  for lead in leads
    fun = (callback) ->
      console.log(lead.state)
      State.get lead.state, (e, state) ->
        if !state or state.canBeCalled(self.currentTime())
          return callback(null, lead._id.toString)

        return callback(null, null)

    funcArr.push(fun)

  async.parallel funcArr, (e, r) ->
    if (e)
      return cb(message:'No leads can be called at the current time', null)

    id = _.compact(r)
    id = r[0] if r.length

    if (!id || !id.length)
      return cb(message:'No leads can be called at the current time', null)

    lead = _.filter leads, (l) -> return l._id.toString() == id

    # Code handling 
    @takeLead(lead, user, cb)

我 90% 确定问题是我正在创建的这个数组没有像我想的那样被分配,但我不确定。有人知道我在这里做错了什么吗?

【问题讨论】:

    标签: javascript asynchronous coffeescript async.js


    【解决方案1】:

    我猜你有一个经典的“循环内闭包”问题:

    for lead in leads
      fun = (callback) ->
        # some stuff that uses 'lead'...
    

    问题是所有fun 函数都将引用完全相同的lead,当这些函数执行时,lead 将引用它在循环中的最后一个值。

    来自fine manual(该部分的底部):

    当使用 JavaScript 循环生成函数时,通常会插入一个闭包包装器以确保循环变量被封闭,并且所有生成的函数不只是共享最终值。 CoffeeScript 提供了 do 关键字,它立即调用传递的函数,转发任何参数。

    听起来很熟悉?您可能希望在每次迭代中获取 lead 的值,而不是像这样拖着 lead 本身:

    for lead in leads
      do (lead) ->
        fun = (callback) ->
          # What you have now...
    

    【讨论】:

    • 抱歉拖了这么久,我正在使用do(),但它不起作用。最后,这就是我将函数推送到该数组的方式,当时我使用的是与上面不同的东西。最终这就是问题所在!
    猜你喜欢
    • 2014-04-10
    • 2021-05-31
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2017-11-03
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多