如何使函数等待异步调用完成?

JSA*_*ict 3 angularjs

我有一项angularjs服务来获取我的json数据.

// Controller.js file
$scope.data=Events.query();

$scope.getEventtypes = function(){
    angular.forEach($scope.data,function(value, key){
        var arr = [];
        if(key==$scope.month+$scope.year)  {
            for(var i=0; i<key.length; i++) {
                arr.push(value[i].type);
                $scope.eventtypes=arr.unique();
            }
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

在尝试访问value[i].type它时抛出错误无法读取type未定义的属性.我知道这是因为异步调用.

//i want to add success function like this
$http.get('').success(function(data) {
....
});
Run Code Online (Sandbox Code Playgroud)

谁能帮我??如果你建议做一些比这更有效的事情会更好.谢谢

asg*_*oth 6

我使用异步$ http服务(使用jsonp)得到了类似的答案.

基本上你需要:

  • 使用回调或
  • 使用promise对象

承诺:

var promise = service.getHistoricalDataWithQ($scope.symbol, $scope.startDate, $scope.endDate);

promise.then(function(data) {
   $scope.items = data;
});            
Run Code Online (Sandbox Code Playgroud)

回调:

service.getHistoricalDataWithCallback(function (data) {
    $scope.items = data;
}, $scope.symbol, $scope.startDate, $scope.endDate);
Run Code Online (Sandbox Code Playgroud)

请参阅使用$ htp和YQL回答Angular.

看我的jsFiddle.