I'm new to promises and can't solve this syntax problem.
In my .then chain I got this part. I got an array of arrays and would like to add a new property to some objects inside the arrays. Before I do this I have to make a request with googleDirection.directionRequest
this resolves a new promise. But while adding the attribute to the object the object is undefined (I think because the dbResult
is outside of the nested .then chain). I tried different ways but can't solve this.
Hope some body can help me with this.
.then(function(dbResult){
for(var i = 0; i < dbResult.length; i++){
if(dbResult[i].length == 1){
var smallestValue = googleDirection.directionRequest(req.body.startlocation.latitude + "," + req.body.startlocation.longitude, dbResult[i][0].startLatitude + "," + dbResult[i][0].startLongitude,true,false)
.then(function(distance){
var values = [];
for(var j = 0; j < distance.routes.length; j++){
values.push(distance.routes[j].legs[0].distance.value);
}
return Math.min.apply(Math,values);
})
.then(function(value){
return(value);
})
smallestValue.then(function(value){
dbResult[i].tripStartToConstrStart = value;
})
}
}
return dbResult
})
.then(function(dbResult){
console.log(dbResult)
})
This is the error:
(node:8708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot set property 'tripStartToConstrStart' of undefined
(node:8708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot set property 'tripStartToConstrStart' of undefined