javascript - $q.all - 只取那些已解决的

标签 javascript angularjs coffeescript promise q

如果是这样的话:

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() 中,我怎样才能只返回那些已解决的 promise ?

最佳答案

$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

关于javascript - $q.all - 只取那些已解决的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25296960/

相关文章:

ruby-on-rails - 在 coffeescript 中获取 rails view helper 方法

javascript - Ember 绑定(bind) Controller 计算属性未更新

javascript - 如何在 Node js 中找到当前周的星期一?

javascript - 使用 Google map 的 JavaScript 中的作用域和闭包问题

javascript - Uncaught Error : input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`

javascript - 指令模板上的 $document.ready()?

javascript - 将日期分配给另一个变量而不更改初始日期

javascript - 如何在 AngularJS 中动态注入(inject)整个模块?

javascript - 如何修复此 Angular JS 错误 : [$injector:unpr]?

node.js - webstorm 8,如何摆脱警告信息