-1

I receive this bizarre behavior where the output of a key-value-pair of an object is supposedly undefined although it clearly is defined in the object and is being printed out.

My code looks like this:

addLocation(loc: any) {
  this.getLocationGPSFromFirebase(loc.$key).then(result => loc = Object.assign(loc, result));
  console.log(loc);
  this.addLocationToLocalArray(loc);
}

The output of the console.log in the browser is: Object {address: "blablabla", city: Object

{address: "blablabla"…}
address: "blablabla"
latitude: 37.412368
longitude: 6.0755334
$exists: function ()
$key: "uniqueKeyFromFirebase"
__proto__: Object

My code for the object creation and subsequent push to the array:

addLocationToLocalArray(loc: Location) {
  console.log(loc.latitude, loc.longitude);
  this.tourLocs.push({
    address: loc.address,
    latitude: loc.latitude,
    longitude: loc.longitude
  });
}

The output of the console.log(loc.latitude, loc.longitude); is:

undefined, undefined

When I print the array, it looks like this:

[Object]
0: Object
address: "blablabla"
latitude: undefined
longitude: undefined
__proto__: Object
length: 1
__proto__: Array(0)

This is absolutely bizarre behavior and I don't know what causes it.

Spurious
  • 1,903
  • 5
  • 27
  • 53
  • 2
    You have to wait for the promise before calling `addLocationToLocalArray`! There's no way to get it immediately. Calling `then` does not block. – Bergi Jul 31 '17 at 12:06
  • Thanks for the help guys. I wasn't searching for the right terms. Should I delete the question or leave it open? Not sure about the rules around this. – Spurious Jul 31 '17 at 12:10
  • It's closed already, you don't have to delete it. – Bergi Jul 31 '17 at 12:11

1 Answers1

1

You are calling your add function before you get response from the getLocation api. So you should call your method in your callback of api.

this.getLocationGPSFromFirebase(loc.$key)
.then(result => 
    loc = Object.assign(loc, result)
    console.log(loc);
    this.addLocationToLocalArray(loc);
);
Kamesh
  • 1,122
  • 9
  • 12