Infer-On Infer-On - 5 months ago 32
AngularJS Question

Nested promises return undefined

I have a problem with nested promises, inside an angular service I have this method:

this.get = function (matchId, teamId) {
var _key = matchId + '_' + teamId;
var self = this;
var alivePromise = $apiService.alive();
alivePromise.success(function () {
var getPromise = $apiService.get(matchId, teamId);
getPromise.success(function (response) {
self.clearLocal().then(function () {
return self.pushToLocal({ ots: _key, data: response })
.then(function () {
return self.fetchFromLocal(_key);
});
})
});
getPromise.error(function (response) {
return self.fetchFromLocal(_key);
});
});
alivePromise.error(function () {
return self.fetchFromLocal(_key);
});
};

this.fetchFromLocal = function (key) {
return $indexedDB.openStore('teamsheets', function (store) {
store.find(key);
});
}
this.pushToLocal = function (data) {
return $indexedDB.openStore('teamsheets', function (store) {
store.upsert(data);
});
};


Inside a controller I'd like call this method in this manner:

$dataProvider.get(MATCH_ID, TEAM_ID)
.then(function (result) {
$scope.teamsheet = result;
$scope.masterCopy = JSON.parse(JSON.stringify(result));

});


But I retrieve always the following error:

angular.min.js:107 TypeError: Cannot read property 'then' of undefined
at new <anonymous> (team-sheet-details-controller.js:3)
at Object.e [as invoke] (angular.min.js:39)
at Q.instance (angular.min.js:80)
at L (angular.min.js:61)
at g (angular.min.js:54)
at g (angular.min.js:54)
at angular.min.js:53
at angular.min.js:20
at m.$eval (angular.min.js:132)
at m.$apply (angular.min.js:133)


What I am doing wrong?

Answer

if this.get is your get function on $dataProvider then try this code:

this.get = function (matchId, teamId) {
    var _key = matchId + '_' + teamId;
    var self = this;

    return $apiService.alive().then(function () {
        return getPromise = $apiService.get(matchId, teamId);
        getPromise.success(function (response) {
            self.clearLocal().then(function () {
                return self.pushToLocal({ ots: _key, data: response })
                .then(function () {
                    return self.fetchFromLocal(_key);
                });
            })
        });
        getPromise.error(function (response) {
            return self.fetchFromLocal(_key);
        });
    }, function () {
        return self.fetchFromLocal(_key);
    });
};
Comments