我之前已经阅读了一些有关角度承诺的论坛帖子,但无法在我的实例中使用它。我使用nodejs / locomotive作为后端,Angular作为前端。
我在控制器中有以下代码,基本上我想使用slide.path的路径,我将如何使用promises进行此操作?我们将非常感激地提供任何帮助。
function ProductCtrl($scope, $http, $q) {
$scope.events = [];
$scope.times = [];
var html = [];
var chapters = [];
var path;
//var paPromise = $q.defer();
$http({
url: '/show',
method: 'GET',
params: { eventid:$scope.$routeParams.eventid}
}).success(function(response, code) {
$scope.events = response;
angular.forEach($scope.events.slides, function(slide) {
$http({
url: '/upload',
method: 'GET',
params: {uploadid: slide.upload.toString()}
}).success(function(response, code) {
return "http://www.example.com/"+response.path;
},path);
slide.path = path;
chapters.push(slide);
});
});
}
答案 0 :(得分:4)
你可以使用$ q.all来完成这个多重承诺问题。像这样:
function ProductCtrl($scope, $http, $q) {
$scope.events = [];
$scope.times = [];
var html = [];
var path;
function fetchChapter() {
var chapters = [];
var httpPromise = $http({
url: '/show',
method: 'GET',
params: {
eventid: $scope.$routeParams.eventid
}
});
//Return the value http Promise
return httpPromise.then(function (response) {
$scope.events = response;
var promises = [];
angular.forEach($scope.events.slides, function (slide) {
var inPromise = $http({
url: '/upload',
method: 'GET',
params: {
uploadid: slide.upload.toString()
}
}).then(function (response, code) {
//each promise makes sure, that he pushes the data into the chapters
slide.path = "http://www.example.com/" + response.path;
chapters.push(slide);
});
//Push the promise into an array
promises.push(inPromise);
});
//return the promise from the $q.all, that makes sure, that all pushed promises are ready and return the chapters.
return $q.all(promises).then(function () {
return chapters;
});
});
}
fetchChapter().then(function(chapters){
//populate here
});
}
httpPromise将从$ q.all返回承诺。
编辑:如何获取数据
包裹一个函数,我使用fetchChapter
并将函数传递给then
,将会有您需要的值作为参数。