0

I have a function:

getCoordinates: function() {
        geoLocation.getCurrentLocation().then(function(location) {
            return "latitude: " + location.latitude + " longitude:" + location.longitude;
        });
    }

Which returns undefined, but when I instead do:

getCoordinates: function() {
        geoLocation.getCurrentLocation().then(function(location) {
            console.log("latitude: " + location.latitude + " longitude:" + location.longitude);
        });
    }

and run the same function I get:

"latitude: 4X.XXXXXX longitude:-12X.XXXXXXX"

I don't understand why it is returning undefined when the data must be defined or it wouldn't log to the console. Is this some kind of timing issue? What am I missing?

HelloWorld
  • 2,480
  • 3
  • 28
  • 45

1 Answers1

4

You are only returning from the then callback, not from the getCoordinates function (which in fact doesn't return anything, hence undefined).

This is unsolvable for asynchronous callbacks in general. In your case, the best solution will be to simply return the promise that you are already creating and which will fulfill with the value you expect in the future.

getCoordinates: function() {
    return geoLocation.getCurrentLocation().then(function(location) {
//  ^^^^^^
        return "latitude: " + location.latitude + " longitude:" + location.longitude;
    });
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I have tried the solution you present above. When I do that the promise object itself is returned: [object Promise] – HelloWorld Dec 14 '16 at 02:36
  • Yes, that's expected. You cannot return the data, as it doesn't exist yet. Please read the linked question. – Bergi Dec 14 '16 at 02:38
  • 1
    Instead of doing `console.log(getCoordinates())`, you'll need to do `getCoordinates().then(console.log)`, and deal with the fact that you don't get the log immediately. – Bergi Dec 14 '16 at 02:39
  • OK I understand the problem now. Thanks buddy! – HelloWorld Dec 14 '16 at 02:41