Search code examples
javascriptionic-frameworkngcordova

.then not waiting for return function when using cordovaGeolocation


I turn once again to StackOverFlow in my pursuit to learn Javascript and Ionic.

I have created the following factory function:

.factory('GeoService', function($ionicPlatform, $cordovaGeolocation) {

  var positionOptions = {timeout: 10000, enableHighAccuracy: true};

  return {
    getPosition: function() {
      return $ionicPlatform.ready()
        .then(function() {
          return $cordovaGeolocation.getCurrentPosition(positionOptions);
        })
    }
  };

});

Which obtains the GPS coordinates. To call this function I am doing the following:

        GeoService.getPosition()
            .then(function(position) {
                //Obtain geolocation information
                console.dir(position.coords)

                return position.coords;
            }, function(err) {
                console.log('getCurrentPosition error: ' + err);
            }).then(function(data) {
                console.dir(data)

                //make http request with the information
            })

The issue that I have is that the second .then is not waiting for the GeoService.getPosition() to resolve before attempting to send the information via http. I suspect I need to use something along the lines of q.all but I am just not sure.

Many thanks


Solution

  • You should define your own promise

    .factory('GeoService', function($q,$ionicPlatform, $cordovaGeolocation) {
    
    
      function getPosition(){
    
        return $q(function(resolve, reject) {
            var positionOptions = {timeout: 10000, enableHighAccuracy: true};
            $cordovaGeolocation.getCurrentPosition(positionOptions)
            .then(function(position){
                 resolve(position); 
            }, function(error){
               reject(error); 
            }); 
        })
    
      } 
      return {
        getPosition: getPosition
      };
    
    });