After spending all morning troubleshooting, I finally got this code to run successfully and add elements to the array. However, a perplexing issue arises when I try to return the array as it comes back empty. It's been a frustrating morning of debugging for me.
details.getDetails = function(idSet, pageNum) {
var page = idSet[pageNum],
placeDetails = [],
i;
for(i=0; i<page.length; i++){
ngGPlacesAPI.placeDetails({placeId: page[i]})
.then(function(data){
response = data;
placeDetails.push(response);
console.log(placeDetails) //This shows the loop running and the array being populated
})
}
return placeDetails;
console.log(placeDetails) //This returns empty array
};
I suspected that the issue might be related to asynchronous data handling, as Rayon mentioned. I attempted to implement a promise-based solution but I'm unsure if I've done it correctly. Here is the modified code snippet:
.factory('details', function(ngGPlacesAPI, $q){
var response,
details = {};
details.getDetails = function(idSet, pageNum) {
var page = idSet[pageNum],
deferred = $q.defer,
placeDetails = [],
i;
for(i=0; i<page.length; i++){
ngGPlacesAPI.placeDetails({placeId: page[i]})
.then(function(data){
response = data;
placeDetails.push(response);
})
}
deferred.resolve(placeDetails);
console.log(deferred.promise);
return deferred.promise;
};
// Return Details Object
return details;
});