嵌套异步函数不能及时返回数据的问题

时间:2015-03-16 12:29:53

标签: javascript angularjs

我依赖于一个组件,即Angular Material Autocomplete,需要一个返回值的函数

不幸的是,我不确定如何从下面的嵌套异步函数(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...
};

当addressAutocomplete函数完成时,results var已经被返回,它当然是一个空数组......

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您需要公开调用与chooseAddress的被调用者异步的事实。您可以通过返回promise来实现此目的。

将实施更新为

$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;
};

然后拨打chooseAddress,如

$scope.chooseAddress(input).then(function(result){
    // the result will be available here
});