[英]Only trigger a function in the last iteration of a forEach loop
以下代码检查字段是否为文件类型,以及其中是否有实际文件。 如果是这种情况,请上传照片并更新建筑物。 如果不是这种情况,请使用旧照片更新建筑物:
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)
}
})
它运行良好,但是由于this.updateBuilding(building)
处于循环中,因此被称为倍数。
如何做到这一点,使其仅在上一次迭代中被调用?
您可以检查fields.lengths 字段数组 ,它将是fields数组的最后一个元素。
if(fields[fields.length - 1]){
// Loop control will enter in this block in last iteration
// Enter your update code inside this
}
希望这就是您想要的。
MDN documentation
建议对forEach
的回调具有三个参数:
您可以使用它来检查当前元素的索引是否等于数组的最后一个索引:
fields.forEach((field, index, array) => {
// YOUR CODE
if (index === array.length - 1) {
// DO SOMETHING
}
});
在每次迭代中使用带有增量的count变量,如果field.length等于count变量,则使用if条件调用该函数
var count = 0;
var fields_length = fields.length;
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
})
} else {
building.logo = this.building.logo // to prevent updating logo
building.floorplan = this.building.floorplan // to prevent updating logo
}
if(count == fields_length){
this.updateBuilding(building)
}
count++
})
尝试:
var len = fields.length;
var counter = 0;
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
/* checking if it's the last loop */
if(counter == len - 1)
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)
}
counter = counter + 1;
})
如何创建一些变量以在循环中保存适当的值; 循环之后,您可以使用这些变量在构建时运行更新。
更新
哦,您实际上需要更新的回调。 您在循环中进行了一些异步操作???
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.