从数组中同步删除值

Synchronous removing values from array

对于网络界面,可以删除某些属性。此属性存储在一个数组中,我将遍历这些数组并删除 selected 的。

因为我在每次删除后写入属性文件,我猜它有时会因为异步化而变得混乱?

我select属性A、B和C。

A将被删除,文件将被写入没有A -> [B,C].

下一行 B will be removed,但是 C also started 并且还有 B in his memory

B 将从上一步中删除并写入文件,但之后 C 将被删除并且文件将与 B 一起写入。

结果 -> Remaning 数组,B 仍在其中。

deleteSelected() {
   let count = 0;
   for (const propertyId of this.selectedProperties) {
     this.metadataPropertyService.deleteProperty(this.packageName, propertyId).then(
       result => {
         count++;
         if (count === this.selectedProperties.length) {
           this.ngOnChanges();
         }
       });
   }
 }`
public IData deleteProperty(IData pipeline){
       PropertyInput propertyInput = IDataToObjectParser.getDeletePropertyInput(pipeline);
       List<Property> properties = new ArrayList<>(getProperties(propertyInput.getPackageName()));
       Property property = getProperty(properties, propertyInput.getId());
       if(properties.remove(property)){
           return writeProperties(FileUtils.getFile(propertyInput.getPackageName(), configurations), properties);
       }
       Error error = new Error("MTD-WR-01", "TECHNICAL","Cannot remove property with id " + propertyInput.getId());
       return ObjectToIDataParser.getStatus(new Status(State.ERROR, error));
   }

我预计 .then() 代码将 运行 同步并且 deleteProperty 将 运行 一个接一个。有人有替代方案吗?

您可以使用 async/await 替换 .then()

async deleteSelected() {
       let count = 0;
       for (const propertyId of this.selectedProperties) {
        await result =  this.metadataPropertyService.deleteProperty(this.packageName, propertyId);
           count++;
           if (count === this.selectedProperties.length) {
               this.ngOnChanges();
             }
       }
     }

您可以使用 async/await 方法:

async function deleteSelected() {
    for (const propertyId of this.selectedProperties) {
        await this.metadataPropertyService.deleteProperty(this.packageName, propertyId)
    }
    this.ngOnChanges();
}

您不再需要 count 变量,因为您是 运行 同步删除操作,所以当 for 循环结束时,您已经删除了所有元素。