【问题标题】:$q.all - take only those that resolved$q.all - 只取那些已解决的
【发布时间】:2014-10-07 10:48:24
【问题描述】:

如果是这样:

getCol = (colId)->
   dfrd = $q.defer()
   if colId == "bacon"
       dfrd.reject()
   else
       dfrd.resolve colId
   dfrd.promise


getCols = (columns)->
   $q.all(_.map(columns, (cs)-> getCol(cs)))


getCols(['eggs','juice']).then (cols)->
   console.log cols                    # works



getCols(['eggs','juice','bacon']).then (cols)->
   console.log cols                  # not even getting here

那么,在getCols() 中,我怎样才能只返回那些已解决的承诺?

【问题讨论】:

  • 这是预期的(只有当所有的承诺都是resolved 时才会执行 $q 成功),如果出现错误,您可以毫无价值地解决。所以你会在数组中得到对应的未定义值。
  • 您使用的是Q,还是Angular 的$q? Please choose the tags appropriately.
  • 好吧,我想我可以很容易地注入 Q 而不是 angular,如果它在这种情况下派上用场
  • Here 这是与 $q 非常接近的副本,是否令人满意?

标签: javascript angularjs coffeescript promise q


【解决方案1】:

$q.all 仅在all of the promises you pass it 已解决时才解决。比如说,只有在所有 4 个小部件都加载后才显示仪表板。

如果您不希望这种行为,即您想尝试显示尽可能多的列,则可以成功解析,您将不得不使用不同的方法。

loadedColumns = []

getCols = (columns) ->
  for col in columns
    willAdd = addColumn(col) # add column needs to store columns in the "loadedColumns" area, then resolve
    willAdd.then buildUI
    willAdd.catch logError


# Because this method is debounced, it'll fire the first time there is 50 ms of idleness
buildUI = _.debounce ->
  // Construct your UI out of "loadedColumns"
, 50

【讨论】:

  • 嗯...有趣...谢谢,我会试试看
猜你喜欢
  • 1970-01-01
  • 2013-12-29
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 2015-04-09
  • 2016-08-10
  • 1970-01-01
相关资源
最近更新 更多