如何实现承诺功能,以便我可以摆脱超时,如果可能的话?我从工厂'Prim'获得了一些数据,功能看起来像是:
$scope.getPre = function(id){
var url = WEB_API.MainUrl + '/api/prim/' + id +'/' + $window.sessionStorage.getItem('idsom');
Prim.getprim(function(data) {
$scope.prim1 = data;
$scope.prim = $scope.prim1[0];
}, url);
$scope.$apply();
}
和我想要摆脱的超时:
setTimeout(function() { // it can't work without timeout
$scope.getPre($routeParams.idprim);
}, 100);
答案 0 :(得分:0)
您的函数应该返回一个承诺,因此您可以使用.then()
:
$scope.getPre = function(id){
var deferred = $q.defer()
var url = WEB_API.MainUrl + '/api/prim/' + id +'/' + $window.sessionStorage.getItem('idsom');
Prim.getprim(function(data)
$scope.prim1 = data;
$scope.prim = $scope.prim1[0];
deferred.resolve();
}, url);
return deferred.promise;
}
然后就这样使用它:
$scope.getPre($routeParams.idprim).then(function () {
// Do whatever you did after setTimeout
});