I'm using Angular's $q service to return a promise. In my function the promise is resolved when I find the picture(a object) by a id(key value) which I'm searching in a array of pictures. I get the pictures if array is empty else I start searching. The function is working but I'm unable to make it into a promise.
My service method:
picturesService.getCurrentPic = function (pictureId) {
console.log("process started, id: ", pictureId);
if(picturesService.pictures.length == 0){
console.log("empty");
picturesService.getPictures().then(function(data){
picturesService.pictures = data.data.children;
picturesService.getCurrentPic(pictureId);
});
}else{
var deferred = $q.defer();
console.log("not empty");
for (var i = picturesService.pictures.length - 1; i >= 0; i--) {
if(picturesService.pictures[i].data.id == pictureId){
console.log("found: ", picturesService.pictures[i].data);
deferred.resolve(picturesService.pictures[i].data);
break;
};
};
return deferred.promise;
};
};
Controller code:
picturesService.getCurrentPic(vm.pictureId).then(function(data){
vm.currentPic = data;
console.log("currentPic: ", vm.currentPic);
});
Error that I'm getting:
Cannot read property 'then' of undefined