简体   繁体   中英

Execute Code only after Multiple Promises Fulfilled in EmberJS

I have an EmberJS ArrayController. I want to have a computed property on this controller, neurons , that is a subset of the model property. The subset is computed based on a toggle button in the sidebar which is bound to currentDataset . Another computed property, activePlots then depends on neurons ; the Neuron model has a hasMany relationship to Plot , and activePlots loads all the plot objects associated with each neuron object in neurons .

Currently I'm trying to do this with mapBy , but I'm running into a problem. Each retrieval of a Neuron object's plots returns a 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?

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

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. If one is rejected, the all() promise is rejected.

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)

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)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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