Ok I'm new to JavaScript programming and I'm really struggling with the async stuff. I have tried to show my example below:
Controller
$scope.handleClick = function(stuff) {
var promise = fetchOtherStuffs(stuff.id1);
var promiseTwo = fetchOtherStuffs(stuff.id2);
$q.all([promise, promiseTwo]).then(function(data) {
// fails because data is undefined
console.log(data[0].length);
console.log(data[1].length);
});
};
var fetchOtherStuffs = function(stuffId) {
return $http.get('http://localhost/myapi/stuff/' + stuffId)
.then(function(theStuffs) {
var promises = [];
for (var i = 0; i < theStuffs.data.length; i++) {
var otherStuffId = theStuffs.data[i].otherStuffId;
promises.push(
$http.get('http://localhost:8085/myapi/otherstuff/'
+ otherStuffId));
}
$q.all(promises).then(function(data){
var result = [];
for (var i = 0; i < promises.length; i++) {
result.push(data[i].data[i]);
}
// this works and the data count is as expected
console.log('returning: ' + result.length);
return result;
});
});
};
So I need to:
- call
myapi/stuff
- take the result of that call (which can be many Objects) and call the
/myapi/otherstuff
for each of those Objects - return all of those Objects from otherstuff back to the handleClick method
I really don't know how to implement the fetchOtherStuffs method so the promise is returns actually returns a value when it's needed in the handleClick method.
Thanks a lot.