1

I rely on a component i.e. Angular Material Autocomplete that requires a function that returns a value.

Unfortunately, I am not sure how to return something in due time from the nested asynchronous function below (addressAutocomplete()):

$scope.chooseAddress = function (input) {
    var results = [];
    if (input) {
        geolocationService.addressAutocomplete(input, function (data) {
            results = data.predictions;//Will be fired asynchronously and too late...
        });
    }
    return results;//I have to return something from my function...
};

By the time the addressAutocomplete function has completed, the results var has already been returned and it is of course an empty array...

Can someone please help?

balteo
  • 23,602
  • 63
  • 219
  • 412

1 Answers1

2

You need to expose the fact that the call is asynchronous to the callees of chooseAddress. You can achieve this by returning a promise.

Update the implementation to

$scope.chooseAddress = function (input) {
    var deferred = $q.defer();

    if (input) {
        geolocationService.addressAutocomplete(input, function (data) {
            deferred.resolve(data.predictions);
        });
    } else {
        deferred.resolve([]);
    }
    return deferred.promise;
};

You then call chooseAddress like

$scope.chooseAddress(input).then(function(result){
    // the result will be available here
});
thomaux
  • 19,133
  • 10
  • 76
  • 103