【问题标题】:How to make _.each handle both 'array' and 'array of array' in $.when done handler如何使 _.each 在 $.when done 处理程序中同时处理“数组”和“数组数组”
【发布时间】:2016-10-07 01:59:10
【问题描述】:

我必须执行一些 json 调用并对结果应用回调。调用次数在运行前是未知的。因此,我使用$.when.apply 将一组承诺传递给when

  jsonPromises     = []
  newContentActions = []
  for model in models
      jsonPromises.push contentCreator.create(model)
      action = new ActionHandler model
      newContentActions.push action

  $.when.apply($, jsonPromises)
  .then (args...) =>
    _.each args, (result, idx) =>
      return unless result[1] is 'success'
      action = newContentActions[idx]
      action result[0]

它或多或少地按预期工作。当有多个承诺时,$.whenthen 处理程序将获得一个数组数组(例如,在 Chrome 开发控制台中看到的[[Object, "success", Object], [Object, "success", Object]])。然后_.each 可以正确解压到result, idx

但是,如果只有 1 个承诺,我只会在 thenhandler 中获得一个数组。它混淆了_.eacheach 解包单个数组并生成 3 个函数调用。我的应用程序失败了。

为了解决这个问题,我对承诺的数量进行了额外检查。只有一个的时候我不会用$.when

  if jsonPromises.length is 1
    jsonPromises[0].done (model) =>
      action = newContentActions[0]
      action model
  else
    $.when.apply($, jsonPromises)
    .then (args...) =>
      _.each args, (result, idx) =>
        return unless result[1] is 'success'
        action = newContentActions[idx]
        action result[0]

这是实现此结果的唯一方法吗?有没有办法去掉 jsonPromises.length is 1检查?

【问题讨论】:

    标签: jquery coffeescript underscore.js


    【解决方案1】:

    如果您看到 jsonPromises.length 为 1,我的解决方案是将 args 包装在一个数组中

      $.when.apply($, jsonPromises)
      .then (args...) =>
        args = [args] if jsonPromises.length is 1
        _.each args, (result, idx) =>
        return unless result[1] is 'success'
        action = newContentActions[idx]
        action result[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      相关资源
      最近更新 更多