0

I am trying to return the output of a promise. However, I am just getting the actual promise, instead of the value.

What am I doing wrong?

Here's my code:

$rootScope.distance = function(lon1, lat1) {

    var deferred = $q.defer();

    $cordovaGeolocation.getCurrentPosition()
        .then(function (position) {
            deferred.resolve(position);
        }, function(err) {

        });
    return deferred.promise;


}

...and the result

enter image description here

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Patrick Reck
  • 11,246
  • 11
  • 53
  • 86
  • I'm not sure what you're aiming for but that's what I would expect... you need to call `then` on the returned promise. When it's resolved your `then` callback will be invoked with the data you need (`position` in this case). If your code is as you've shown you don't need to bother with the `deferred` stuff as you can just return the promise returned by `$cordovaGeolocation.getCurrentPosition` directly. – James Allardice Sep 10 '14 at 12:37
  • I am aiming for not having to call the `.then` – Patrick Reck Sep 10 '14 at 12:37
  • Then you should not use a promise :D – Florian Gl Sep 10 '14 at 12:38
  • 3
    You can't get rid of the `then`. Promises do not magically make asynchronous code synchronous. You return a promise, *then* do something with the value it resolves to. – James Allardice Sep 10 '14 at 12:38
  • That is why I am trying to use `$q` to return the value when it's resolved – Patrick Reck Sep 10 '14 at 12:41
  • 1
    @PatrickReck - You can't return the value when it's resolved. It has nowhere to return to. What you can do (and what you *are* doing) is return a promise for that value and do something with it when it's resolved. – James Allardice Sep 10 '14 at 12:43
  • 1
    Btw, `$cordovaGeolocation.getCurrentPosition()` seems to already return a promise. Your code currently is the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572) – Bergi Sep 10 '14 at 13:01
  • 1
    You can't make an asynchronous operation synchronous. Promises don't do that. They just change the syntax but you still need to pass a callback. Only instead of passing the callback to the asynchronous function the traditional way you pass it to the promise's then function. – slebetman Sep 10 '14 at 13:05

1 Answers1

0

Since a promise is asynchronous, you can't get its value directly (synchronous) after calling the promise returning function. You could do this

$rootScope.updateDistance = function(lon1, lat1) {
    $cordovaGeolocation.getCurrentPosition()
        .then(function (position) {
            $rootScope.distance = position;
        });
}
Florian Gl
  • 5,984
  • 2
  • 17
  • 30