我正在尝试从我的代码上的嵌套函数返回一个值,但每当我试图显示它时它都会返回undefined。这是我的代码:
var calculateAlbum = function (albumPath,albumName) {
return photoService.getPhotos(albumPath,albumName)
.success(function (data){
var status = data.myphotos.status;
if(status == "ok"){
photoService.myphotosPhotoList()
.success(function(data){
$scope.allPhotoListTotal = {};
var getAllPhotoList = data.config.nas_sharing;
$scope.allPhotoListTotal = getAllPhotoList.count;
});
}
});
}
返回一个值:
calculateAlbum(albumPath,fileName).then(function(data) {
var gettotal = $scope.allPhotoListTotal;
console.log(gettotal);
});
在控制台中返回值后。它发送给我undefined。对此最好的是什么?
答案 0 :(得分:2)
你忘了回复photoService.myphotosPhotoList
的承诺。
当状态不正常时,您也忘记拒绝第一个承诺(您可以测试这种情况)。
function calculateAlbum (albumPath,albumName) {
return photoService.getPhotos(albumPath,albumName)
.then(function (data){
var status = data.myphotos.status;
if(status == "ok") {
return photoService.myphotosPhotoList()
.then(function(data){
$scope.allPhotoListTotal = {};
var getAllPhotoList = data.config.nas_sharing;
$scope.allPhotoListTotal = getAllPhotoList.count;
});
}
else {
return $q.reject("status not ok");
}
});
}
答案 1 :(得分:1)
您的代码中有两个承诺,但您只是链接第一个(外部)承诺。你的内心承诺设定了你想要的价值,因此你需要等待你的内心承诺解决才能使用它。
一种方法是注入promise服务$q
,然后返回自己的promise对象。
var calculateAlbum = function (albumPath,albumName) {
var deferred = $q.defer();
photoService.getPhotos(albumPath,albumName)
.success(function (data){
var status = data.myphotos.status;
if(status == "ok"){
photoService.myphotosPhotoList()
.success(function(data){
var getAllPhotoList = data.config.nas_sharing;
$scope.allPhotoListTotal = getAllPhotoList.count;
deferred.resolve(data)
});
}
});
return deferred.promise;
}
答案 2 :(得分:1)
calculateAlbum返回外部调用完成时满足的promise
,但它没有考虑内部执行。你需要在内部成功函数内返回promise
才能等待另一个异步方法。在这里,我们将$q
的力量发挥到极致。
var calculateAlbum = function (albumPath,albumName) {
return photoService.getPhotos(albumPath,albumName)
.success(function (data){
var status = data.myphotos.status;
var defer = $q.defer();
if(status == "ok"){
photoService.myphotosPhotoList()
.success(function(data){
$scope.allPhotoListTotal = {};
var getAllPhotoList = data.config.nas_sharing;
$scope.allPhotoListTotal = getAllPhotoList.count;
defer.resolve(); //Async execution end here
})
.error(defer.reject);
}
else
defer.reject();
return defer.promise;
});
}
注意:这是一种反模式,但由于photoService.myphotosPhotoList()
仅在某些时间执行,因此没有其他办法。
编辑:实际上还有其他方式。看看icycool的解决方案