简体   繁体   English

仅在EmberJS中实现多次承诺后执行代码

[英]Execute Code only after Multiple Promises Fulfilled in EmberJS

I have an EmberJS ArrayController. 我有一个EmberJS ArrayController。 I want to have a computed property on this controller, neurons , that is a subset of the model property. 我想在这个控制器上有一个计算属性, neurons ,它是model属性的一个子集。 The subset is computed based on a toggle button in the sidebar which is bound to currentDataset . 子集是基于侧栏中的切换按钮计算的,该切换按钮绑定到currentDataset Another computed property, activePlots then depends on neurons ; 另一个计算属性, activePlots则依赖于neurons ; the Neuron model has a hasMany relationship to Plot , and activePlots loads all the plot objects associated with each neuron object in neurons . Neuron模型具有hasMany关系Plot ,并activePlots加载所有的情节对象在每个神经元的对象关联neurons

Currently I'm trying to do this with mapBy , but I'm running into a problem. 目前我正在尝试使用mapBy ,但我mapBy了一个问题。 Each retrieval of a Neuron object's plots returns a PromiseArray . 每次检索Neuron对象的plots返回PromiseArray I need to manipulate all the returned plots at once. 我需要立即操纵所有返回的图。 I understand I can call then on the promise result of an individual call get('plots') , but how do I execute code only after the get('plots') call has returned for ALL neurons? 我明白我可以打电话then对单个呼叫的承诺结果get('plots')但我怎么只有后执行代码get('plots')调用返回的所有神经元?

neurons: ( ->
    @get('model').filterBy('dataset', @get('currentDataset'))
).property('model', 'currentDataset'),

activePlots: ( ->
  plots = @get('neurons').mapBy('plots')
  # ...code to execute after all plots have loaded
).property('neurons')

UPDATE: Picture of console output from console.log(plotSets) inside the then callback to 更新:从控制台输出图片console.log(plotSets)then回调

Ember.RSVP.all(@get('neurons').mapBy('plots')).then (plotSets) -> 
  console.log(plotSets)

在此输入图像描述

There is a handy method for combining promises: Ember.RSVP.all(ary) takes an array of promises and becomes a promise that is resolved when all the promises in the input array are resolved. 有一种方便的方法来组合promises: Ember.RSVP.all(ary)接受一个promises数组,并成为一个promise,当输入数组中的所有promise都被解析时,它将被解析。 If one is rejected, the all() promise is rejected. 如果拒绝一个,则拒绝all()保证。

This is very handy, for example, when firing off multiple parallel network requests and continuing when all of them are done. 这非常方便,例如,当启动多个并行网络请求时,并在完成所有这些请求时继续。

In addition to what Steve said you can watch the nuerons.length and use Ember.scheduleOnce to schedule an update (guessed coffeescript below) 除了Steve说你可以观看nuerons.length并使用Ember.scheduleOnce来安排更新(下面猜到了coffeescript)

activePlots: [],

watchNuerons: ( ->
  Ember.run.scheduleOnce('afterRender', this, @updatePlots); 
).observes('nueron.length'),

updatePlots: ( ->
  plots = @get('neurons').mapBy('plots')
  # ...code to execute after all plots have loaded
  @set('activePlots', plots)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM