无法等待函数返回(使用promises?)在角度控制器中工作

时间:2013-05-17 09:02:19

标签: angularjs

我正在尝试在saveInterview完成后执行的Angular控制器中获取以下findTimelineEntries函数:

$scope.saveInterview = function() {
        $scope.interviewForm.$save({employeeId: $scope.employeeId}, function() {
            $scope.findTimelineEntries();
        });
    };

保存操作会添加或编辑也属于时间轴条目的数据,因此我希望显示更新的时间轴条目。 首先我尝试将其更改为:

$scope.saveInterview = function() {
        var functionReturned = $scope.interviewForm.$save({employeeId: $scope.employeeId});
        if (functionReturned) {
            $scope.findTimelineEntries();
        }
    };

稍后:

$scope.saveInterview = function() {
        $scope.interviewForm.$save({employeeId: $scope.employeeId});
    };

    $scope.saveInterview.done(function(result) {
        $scope.findTimelineEntries();
    });

最后,我发现了一些关于承诺的信息,所以我尝试了这个:

    $scope.saveInterview = function() {
        $scope.interviewForm.$save({employeeId: $scope.employeeId});
    };

    var promise = $scope.saveInterview();
    promise.done(function() {
        $scope.findTimelineEntries();
    });

但不知何故,它根据http://nurkiewicz.blogspot.nl/2013/03/promises-and-deferred-objects-in-jquery.html以这种方式工作的事实并不意味着我可以在$ scope.someFuntcion = function()函数上使用相同的方法:-S

1 个答案:

答案 0 :(得分:1)

以下是使用promises的示例。首先,您需要在控制器中加入$ q。

$scope.saveInterview = function() {
   var d = $q.defer();
   // do something that probably has a callback. 
   $scope.interviewForm.$save({employeeId: $scope.employeeId}).then(function(data) {
      d.resolve(data);  // assuming data is something you want to return. It could be true or anything you want.
   });


   return d.promise;

}