【问题标题】:Synchronous removing values from array从数组中同步删除值
【发布时间】:2019-09-09 08:58:25
【问题描述】:

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

因为我在每次删除后都会编写属性文件,所以有时会因为我猜的异步而将其混在一起?

我选择属性 A、B 和 C。

A会被移除,文件会写入不带A -> [B,C].

下一行 B will be removed,但 C also started 仍然有 B in his memory

B 将从上一步中删除并写入文件,但随后将删除 C 并将 B 写入文件。

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

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 将一一运行。有人有替代方案吗?

【问题讨论】:

    标签: javascript java arrays asynchronous synchronous


    【解决方案1】:

    您可以使用async/await 方法:

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

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

    【讨论】:

      【解决方案2】:

      您可以使用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();
                   }
             }
           }
      

      【讨论】:

        猜你喜欢
        • 2019-04-12
        • 2020-06-27
        • 1970-01-01
        • 2023-01-31
        • 1970-01-01
        • 2012-07-22
        • 2016-04-06
        • 2017-03-16
        相关资源
        最近更新 更多