【发布时间】:2017-12-08 21:09:33
【问题描述】:
我在使用数组时遇到了一些问题,我必须在 foreach 中更改并再次使用它。以下是部分代码:
this.selectedDepartementen.forEach(element => {
this.DepID = element.ID;
if (this.USERSDepIDs.indexOf(this.DepID) == -1) {
this.insertDepartementCoupling(this.DepID, this.USERid, this.AJID, res => {
if (res) {
this.loading = false;
return;
}
this.removeAllFromArray(this.USERSDepIDs, this.DepID, res => {
this.USERSDepIDs = res;
})
})
} else
{
this.updateDepartementCoupling(this.DepID, this.USERid, this.AJID, res => {
if (res) {
this.loading = false;
return;
}
this.removeAllFromArray(this.USERSDepIDs, this.DepID, res => {
this.USERSDepIDs = res;
})
})
}
});
如您所见,我是否调用了函数removeAllFromArray 来删除最后使用的DepID。但是 foreach 不会等待那个函数,它只是继续运行。我猜这是一个异步的东西,但我该如何解决呢?
提前致谢!
编辑
为用户 Duncan 添加函数insertDepartementCoupling。
async insertDepartementCoupling(DepID, USERid, AJID, callback) {
var test = await this.departementService.insertDepartementCoupling(DepID, USERid, AJID).subscribe(
data => this.mockdata = data,
error => {
this.showMessage("error", "Departement koppeling niet gelukt!", "Departement koppeling niet gelukt, zie console voor meer informatie.");
callback(true);
},
() => {
if (this.mockdata._body) {
this.showMessage("error", "Departement koppeling niet gelukt!", "Contacteer de administrator!");
callback(true);
} else {
this.showMessage("succes", "Departement koppeling geslaagd!", "Gebruiker is gekoppeld aan de departement(en).");
callback(false);
}
});
}
【问题讨论】:
-
你能重写你正在使用的其他函数吗?他们正在使用回调,这将很难确保一切都以合理的顺序发生。如果您可以修改它们以返回 Promise,那么代码应该会变得更简单,因为您可以使用 async/await 来扁平化代码。
-
我可以重写一切。你能给我一个小例子,我可以如何使用 async/await 来扁平化代码吗?
标签: javascript angular typescript asynchronous