[英]Return a value from a nested success function in angularjs
我正在尝试从代码上的嵌套函数返回一个值,但是每当我尝试显示它时,它都会返回未定义的值。 这是我的代码:
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);
});
在控制台中返回值之后。 它使我不确定。 最好的方法是什么?
您忘记了返回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");
}
});
}
您的代码中有两个Promise,但是您只是束缚了第一个(外部)Promise。 内部承诺会设置所需的值,因此您需要等待内部承诺解决后才能使用它。
一种方法是注入诺言服务$q
,然后返回自己的诺言对象。
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;
}
当外部调用完成时,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的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.