我使用Angular的$ q服务返回承诺。在我的函数中,当我通过在一系列图片中搜索的id(键值)找到图片(对象)时,promise被解析。如果数组为空,我得到图片,否则我开始搜索。 该功能正在工作,但我无法将其作为承诺。
我的服务方法:
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;
};
};
控制器代码:
picturesService.getCurrentPic(vm.pictureId).then(function(data){
vm.currentPic = data;
console.log("currentPic: ", vm.currentPic);
});
错误,那是我得到:
无法读取属性 '然后' 未定义
所以,如果非要用递归话,我必须这样做,用的诺言?另外,如果我不拒绝承诺(同意不是一个好的做法),它应该仍然是正确的? – y13uc162
使用递归不是一个好习惯,你应该更好地链接承诺:首先加载图像,然后通过id检索图片。不拒绝承诺是一个非常糟糕的主意,不要这样做^^ –