In my current project, I have a promise that interacts with an array of objects. Depending on the value of each item in the array, another function might be called. If not needed, nothing happens and eventually, it resolves to an object. However, there is an issue where it resolves too early. When the state of a car is already known, everything works fine. But if we need to determine the state dynamically, the promise does not wait for the state to be resolved:
getAggregatedData(obj: StorageUnit): Promise<any> {
let stat = {
inStoreCars: 0,
atWorkCars: 0
};
const vm: any = this;
return new Promise((resolve, reject) => {
obj.carsList.forEach(car => {
if (car.inStore) {
stat.inStoreCars++;
} else if (car.atWork) {
stat.atWorkCars++;
}
// unknown state. so check its state
else {
vm.carStateService
.getState(car)
.then(value => {
if (value == 1){
stat.inStoreCars++;
}else{
stat.atWorkCars++;
}
});
}
});
resolve(stat) // returning too early before getState() resolves
});
}
To use this function, I simply call it like this:
getAggregatedData(car).then(stat=>{
console.log(stat)
});