问题嵌套异步函数不及时返回数据 [英] Issue with nested asynchronous function not returning data in time

查看:98
本文介绍了问题嵌套异步函数不及时返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我靠组件上即角材质自动完成,需要一个功能的返回一个值

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

不幸的是,我不知道如何从下面的嵌套的异步函数返回在适当的时候东西( addressAutocomplete()

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

通过addressAutocomplete功能已经完成的时候,结果 VAR已经回来了,这当然是一个空数组...

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

有人可以帮助?

推荐答案

您需要公开的事实,电话是异步 chooseAddress 的被调用者。您可以通过返回承诺实现这一目标。

You need to expose the fact that the call is asynchronous to the callees of chooseAddress. You can achieve this by returning a 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
});

这篇关于问题嵌套异步函数不及时返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆