Search code examples
javascriptangularjspersistencepromisedeferred

AngularJS Defer.promise not working as expected


I'm developing an application using AngularJS & PersistenceJS.

I'm getting trouble dealing with Asynchronous calls as the

Controller :

cars.controller('CrashWidgetOneCtrl',function($scope, $location, $routeParams, CrashServices){  
    if($routeParams.crashId){
        $scope.data = {};
        console.log("CrashID: "+$routeParams.crashId);
        crashId = $routeParams.crashId; 
        alert(1);//Works

        CrashServices.getCrashDetails($scope, crashId).then(function(result){
            console.log(result);
            alert(2);//Never Fires
        });    
    alert(3);//Gets executed
    }else{
        console.log("N");
    }   

});

Services :

cars.factory('CrashServices', function($http, $location, $q, CommonServices,$rootScope, $timeout){
    return{
        getCrashDetails:function($scope, crashId){
        var deferred = $q.defer();          
        // Get user details if any
        $scope.$apply(function(){
            var crashInfoTable = App.CrashInfoTable.all();
            alert(4);
            crashInfoTable.list(null, function (results) { 
                alert(5);//This also doesn't work
                deferred.resolve();
            }); 
        });
        return deferred.promise;
        }
    }

});

Any help will be greatly appreciated. Many thanks.

Note: I am using PersistenceJS.


Solution

  • I dont know if you need the scope.apply. This seemed to work for me:

    getCrashDetails:function($scope, crashId){
        var deferred = $q.defer();          
        // Get user details if any
        App.CrashInfoTable.all().list(null, function(results) { 
            deferred.resolve(results);
        });
        return deferred.promise;
    }