Why is .then not a function?
Matthew Barrera
service.js
.factory('EventService', function ($http, $cordovaSQLite) { return { //some code here.. populateData: function (data) { var items = []; for (i = 0; i < data.length; i++) { items.push(data[i]); } return items; } }
})controller.js
.controller('NearCtrl', function ($scope, $http, $cordovaSQLite, EventService) { EventService.getDataFromDB().then(function (result) { if (result.length > 0) { EventService.populateData(result).then(function (items) { $scope.items = items; }) } else { EventService.getDataFromApi().then(function () { EventService.getDataFromDB().then(function (result) { EventService.populateData(result).then(function (items) { $scope.items = items; }) }) }) } });
})When I'm trying to run this code, I get "TypeError: EventService.populateData(...).then is not a function".
What am I doing wrong?
13 Answers
that service needs to return a promise, not returning the items
populateData: function(data) { var deferred = $q.defer(); var items = []; for (i = 0; i < data.length; i++) { items.push(data[i]); } deferred.resolve(items); return deferred.promise;
}you might not need this though since you could do
var items = EventService.populateData(result);
//Do something with items hereusually promises are used if you're doing something asynchronously. Like calling an API and waiting for a response. In those cases, the response might take seconds to finish THEN the .then function gets called. in your case if you make that function a promise it will be called almost immediately
EDIT: Here's the link to $q Documentation AngularJS: API: $q
Return something that has a promise or just change your calling code:
populateData: return $http.get("www");or
EventService.getDataFromApi().then(function () { EventService.getDataFromDB().then(function (result) { var response = EventService.populateData(result); $scope.items = response; });
}); I have same problem, My device is m1 Mac, I fixed it with npm replace yarn to start