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?

1 Answer 1

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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.