Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

enter image description here

like image 388
Sean Mackesey Avatar asked May 18 '26 08:05

Sean Mackesey


1 Answers

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.

like image 135
Steve H. Avatar answered May 19 '26 21:05

Steve H.