I am working my way through promises and noticed the following. I am listening for changes in my controller like such:
$scope.$on("New Data", function(event, data, ID) {
processTripData(data, ID).then(function(result) {
setTypeDistributionBar(result).then(function(data, labels) {
$scope.distributionLabels = labels;
$scope.distributionData = data;
console.log(labels); // undefined, why?
console.log(data); // defined, as expected
})
})
})
The issue I have is that labels
is undefined, however in the setTypeDistributionBar
function it is defined before it gets resolved:
var setTypeDistributionBar = function(trips) {
var distributionData = [];
var distributionLabels = [];
var types = ['Transport', 'Office & Work'];
return new Promise(function(resolve, reject) {
for(var i=0; i < trips.length; i++) {
var first = trips[i].type.slice(0,1);
var second = trips[i].type.slice(2,3);
distributionLabels.push(types[first-1] + ' -> ' + types[second-1]);
distributionData.push(trips[i].count);
}
if(i === trips.length) {
console.log(distributionLabels); // defined, as expected
resolve(distributionData, distributionLabels);
}
})
}
Question: Why is labels
undefined in the then
part in the first function, but it is defined when logging it just before resolving in the second function?