ffritz ffritz -4 years ago 81
Javascript Question

Promise Resolve returning 2 arrays one undefined

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?

Answer Source

A promise encapsulates one value and one value only. It's easier to consider that a promise is basically the value that a function would return (a function also can only return one value).

So this is not valid:

setTypeDistributionBar(result).then(function(data, labels) {

since function will only receive one argument.

To solve it, you can simply return an object instead of two values:

resolve({
    data: distributionData,
    labels: distributionLabels
});

And then here, you can do something like:

setTypeDistributionBar(result).then(function(r) {
   $scope.distributionLabels = r.labels;
   $scope.distributionData = r.data; 
   // ...
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download