0

My coding style may be bad as I am still learning. I need to know how to handle passing extra parameters to chained promises in Emberjs.

What I am trying to achieve. Lots of promises in my route was looking messy so I decided to write function for each promise

model: function(){
  var self=this,carP,planeP,bikeP;
  carP = self.store.find('car');
  planeP = self.store.find('plane');
  bikeP = self.store.find('bikeP');

  pilotsP = planeP.then(function(planePArr){
    return planePArr.forEach(function(plane){
      return plane.get('pilots') //in plane model: pilots: DS.hasMany('pilot')
    });
  });   
  return Ember.RSVP.hash({
     cars: carP,
     planes: planeP,
     bikes: bikeP,
     pilots: pilotsP,
     city: self.store.createRecord('city'),
     owner: self.store.createRecord('owner'),
  })

}

Action hash of my same route contains

actions: {
  save: function(){
    var self = this;
    return self._saveCity()
                         .then(self._getBikeRiders)
                         .then(self._getCarDrivers)
  }
}
_saveCity: function(){
   return this.currentModel.city.save();
 },
_getBikeRiders: function(value){

 },
_getCarDrivers: function(value){

 }

When i call function self._saveCity() It returns a promise which is good and then pass the resolved value to this._getBikeRiders the _getBikeRiders(value) function has a parameter value which is collected from previous promise in this case save city so we have city name.

Now if in _getBikeRiders(value) function I need to do something with other values i cannot pass anything to it.

example self._getBikeRiders(value,"some paramer) does not pass both.

I lose context inside _getBikeRiders: function() function so I cannot access this ( I get global window).

I dont know how to implement this here Ember.RSVP.Promise could accept context argument

Rigel
  • 882
  • 1
  • 11
  • 32

2 Answers2

1

While locks methods solves your problem I still think that you should understand the solution Stefan Penner suggests. Functions in javascript has a method called bind(thisArg) that lets you redefine this. So in your solution you could as well have solved it like this.

actions: {
  save: function(){
    var self = this;
    return self._saveCity()
                  .then(self._getBikeRiders.bind(self))
                  .then(self._getCarDrivers.bind(self))
  }
}

Using .bind() can be useful in a lot of scenarios so it's a good method to remember. If you need a lot of values from this in Ember it might even be a better solution to change this then passing them all as parameters.

Karl-Johan Sjögren
  • 16,544
  • 7
  • 59
  • 68
0

My suggestion is to wrap the this._getBikeRiders call in a function so you can pass the parameters you need. An example:

actions: {
  let foo = "bar";

  return this._saveCity()
    .then((value) => { this._getBikeRiders(value, foo); })
    .then(this._getCarDrivers());
}
locks
  • 6,537
  • 32
  • 39