0

I'm using a promise within map function and I want to assign every element of array; latitude and longitude properties. Here's the code for example:

$scope.dataset = response.map(function(item, index) {
   GeoCodingService.query({
      address: item.country
    }).$promise.then(function (response) {
      item.latitude = response.results[0].geometry.location.lat;
      item.longitude = response.results[0].geometry.location.lng;
      console.log(item);
      //result {id: "au", count: 593, country: "Australia", latitude: -25.274398, longitude: 133.775136}  
    });

    console.log(item);
    //result {id: "au", count: 593, country: "Australia"}
});

console.log($scope.dataset);
//result [undefined, undefined, undefined, undefined, undefined]

My goal is to obtain all the results with latitude and longitude where I get undefined i.e. in $scope.dataset variable.

Faizan Ali
  • 973
  • 2
  • 16
  • 32
  • As of `console.log($scope.dataset);` in the above, the `query` callbacks haven't run yet; they're **asynchronous**. See the linked question's answers. Separately: Your `map` callback needs to return something, otherwise you end up with an array full of `undefined` (even without the async issue). At least one of the linked question's answers specifically talks about dealing with multiple asynchronous calls. – T.J. Crowder Jul 31 '17 at 10:56
  • I have tried `return item;` just within `then` method, but it returns the same. How can I force `response.map` to be executed first? I'm using it first in the controller. – Faizan Ali Jul 31 '17 at 11:04
  • Again: See the linked question's answers. – T.J. Crowder Jul 31 '17 at 11:05

0 Answers0