如何在for循环中使用angular http rest api保证顺序? [英] How to guarantee sequential order with angular http rest api in for loop?
本文介绍了如何在for循环中使用angular http rest api保证顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个表单,允许您按顺序创建多个资源.
I'm trying to create a form that allows you to create multiple resources in sequential order.
下面的例子
Floor 1
Floor 2
Floor 3
...
Floor 9
<小时>
代码的问题是订单不保证.
我的代码如下
let startAt = this.addAreasForm.controls['startAt'].value
const name = this.addAreasForm.controls['name'].value
const newArea = {name: name}
for (let i = 1; i < (amount + 1); i++) {
newArea.name = name + ' ' + startAt
startAt++
this.areasService.createArea(newArea, parentId)
.subscribe(
area => this.added.emit(area)
)
}
可以像回来一样
Floor 2
Floor 3
Floor 1
Floor 5
Floor 4
<小时>
您如何处理异步 API 调用以保证顺序?
推荐答案
您可以将 async
/await
与 Promise 解决方案一起使用:
You can use async
/ await
for that purpose with the Promise resolve:
for (let i = 1; i < (amount + 1); i++) {
await new Promise(resolve => {
newArea.name = name + ' ' + startAt
startAt++
this.areasService.createArea(newArea, parentId)
.subscribe(
area => {
this.added.emit(area);
resolve();
});
});
}
记得把 async
放在你的函数之前.请参阅此 StackBlitz 上的演示.
Remember to put async
before your function. See this demo on StackBlitz.
这篇关于如何在for循环中使用angular http rest api保证顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文