1

I have two functions that i would like to execute one after the other. One sets one object and the next sets the other object based off of a property of the first object. For some reason, the first object sets fine and i can see the second object properly in the console, yet when i try and set it to my second object it defers back to the first.

setObject1(){
var self = this;
this.Service.getObject1().then(function(data){
  if(data){
    self.Object1 = data.Data;
    self.setObject2();
  }
});
}

setObject2(){
var self2 = this;
this.Service2.getObject2(this.Object1.HRRef).then(function(sdata){
  if(sdata){
    self2.Object2 = sdata[0];
  }
});
}

I can see both objects fine in the console, yet when i try and set the self2.Object2 = sdata[0], it doesnt get set.

Monzingo
  • 391
  • 1
  • 7
  • 17
  • How do you know it's not getting set? Show us how (when) you are trying to access it. – Bergi Feb 23 '17 at 01:07
  • when i hover over sdata[0] in the console, it is showing me that it is data.Data – Monzingo Feb 23 '17 at 01:08
  • I thought you were arguing about `self.Object2`? In any case, it seems like you are confused by [asynchronous inspection](http://stackoverflow.com/q/23392111/1048572) of logged objects, which is non-obvious if you are mutating the objects later. – Bergi Feb 23 '17 at 01:10
  • 1
    It probably is getting set, but you're probably looking at it before it gets set. Remember, these are async operations that finish some time in the future. The only reliable place to examine the results is inside the `.then()` handler. – jfriend00 Feb 23 '17 at 02:59

1 Answers1

0

I would guess its a this problem!

Don't use that function syntax!

Use the arrow syntax: (data) => {}.

In your case:

setObject1() {
   this.Service.getObject1().then(data => {
      console.log(data);
      if(data){
         this.Object1 = data.Data;
         this.setObject2();
      }
   });
}

setObject2() {
   this.Service2.getObject2(this.Object1.HRRef).then(sdata => {
      console.log(sdata);
      if(sdata) {
         this.Object2 = sdata[0];
      }
   });
}
slaesh
  • 16,659
  • 6
  • 50
  • 52