嵌套异步函数未及时返回数据的问题
Issue with nested asynchronous function not returning data in time
我依赖于一个组件,即角度材料自动完成,它需要一个返回值的函数。
不幸的是,我不确定如何在适当的时候从下面的嵌套异步函数(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...
};
当地址自动完成函数完成时,results
var 已经返回,它当然是一个空数组......
有人可以帮忙吗?
您需要向 chooseAddress
的被调用方公开调用是异步的。您可以通过返回承诺来实现这一点。
将实现更新为
$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
});
相关文章:
- AJAX调用并在Node中获取返回数据
- 角度服务未返回数据
- 统计ajax返回数据中的html元素
- 有没有更好的方法可以测量从Ajax调用返回数据所需的总时间
- Imgur API图像搜索未返回数据
- javascript对象显示为null,但object.properties返回数据
- 如何从ajax调用JQuery返回数据
- 试图从嵌套的回调函数返回数据
- NodeJS FS 不从多个文件返回数据
- ajax函数未在C#中返回数据
- 如何在公共js模块中从web服务返回数据
- 将字符串与 JSON 对象组合以返回数据
- 嵌套异步函数未及时返回数据的问题
- NodeJS JSONStream 以一个长字符串的形式返回数据
- 如何使用 HTML 图像请求将数据发送到服务器,或返回数据作为响应
- 从 Angular 模态服务中的模态主体模板返回数据
- jQuery 每个循环返回数据两次
- $.getJSON 在返回数据后不会运行函数
- 如何访问返回数据中的特定json值
- 工厂返回数据后未设置角度$scope