如何在for循环中保证带有角度http rest api的顺序? [英] How to guarantee sequential order with angular http rest api in for loop?
问题描述
我正在尝试创建一个允许您按顺序创建多个资源的表单。
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
代码的问题在于订单不保证。
The problem with the code is that the order is not guarantee.
我的代码在下面
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调用以保证顺序顺序?
How do you handle async api calls to guarantee sequential order? 您可以使用 You can use 请记住将 Remember to put 这篇关于如何在for循环中保证带有角度http rest api的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
推荐答案
async
/ 等待
用于此目的承诺解决: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
在你的功能之前。请参阅此 PLUNKER DEMO 。async
before your function. See this PLUNKER DEMO.