Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  46] [ 1]  / answers: 1 / hits: 6760  / 10 Years ago, wed, april 16, 2014, 12:00:00

I have read a few forum posts before on angular promises but can't get it to work in my instance. I am using nodejs /locomotive for the backend and Angular form the frontend.



I have the following code in a controller, basically I want to use the path to slides.path, how would I go about doing this using promises? any help would be gratefully received.



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);

});

});
}

More From » jquery

 Answers
3

You can use $q.all do get this multiple promise problem done. Like this:



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
});


}



The httpPromise will return the promise from $q.all.



EDIT: How to fetch the data then
Wrap a function around, i did with fetchChapter and pass a function into the then there will be the value you need as a parameter.


[#45988] Tuesday, April 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
billie

Total Points: 101
Total Questions: 114
Total Answers: 98

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;