The following code checks if a field is of type file and if there's an actual file in it. If that's the case, upload the photo and update the buildings. If that's not the case, update the building using the old photos:
fields.forEach(field => {
building[field.name] = field.value || this.building[field.name]
if (field.type === 'file' && !util.isEmpty(field.photo.file)) {
api.uploadPhoto(field.photo.file).then(resp => {
building[field.name] = resp
this.updateBuilding(building)
})
} else {
building.logo = this.building.logo // to prevent updating logo
building.floorplan = this.building.floorplan // to prevent updating logo
this.updateBuilding(building)
}
})
It works well, but since this.updateBuilding(building) is in a loop, it's being called multiples.
How to do it so it's only called in the last iteration?
The MDN documentation suggest that the callback to forEach has three arguments:
You can use it to check whether the current element's index is equal to the last index of the array:
fields.forEach((field, index, array) => {
// YOUR CODE
if (index === array.length - 1) {
// DO SOMETHING
}
});
You can check fields.length of fields array and it will be last element of fields array.
if(fields[fields.length - 1]){
// Loop control will enter in this block in last iteration
// Enter your update code inside this
}
Hope this is what you were looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With