对于网络界面,可以删除某些属性。这些属性存储在一个数组中,我将循环遍历这些数组并删除选定的属性。
因为我在每次删除后写入属性文件,所以有时会因为异步而被混在一起,我猜?
我选择属性 A、B 和 C。
A 将被删除,文件将被写入没有 A -> [B,C]。
下一行B将被删除
,但C也启动了
并且内存中仍然有B
。
B 将从上一步中删除,并且文件将被写入,但随后 C 将被删除,并且文件将被写入,并且 B 会重新写入其中。
结果 -> 剩余数组,其中 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
方法:
async function deleteSelected() {
for (const propertyId of this.selectedProperties) {
await this.metadataPropertyService.deleteProperty(this.packageName, propertyId)
}
this.ngOnChanges();
}
您不再需要 count
变量,因为您正在同步运行删除操作,因此当 for
循环结束时,您已经删除了所有元素。
关于javascript - 同步从数组中删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57850774/