如何在for循环中保证带有角度http rest api的顺序? [英] How to guarantee sequential order with angular http rest api in for loop?

查看:120
本文介绍了如何在for循环中保证带有角度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






代码的问题在于订单不保证。


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?

推荐答案

您可以使用 async / 等待用于此目的承诺解决:

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 在你的功能之前。请参阅此 PLUNKER DEMO

Remember to put async before your function. See this PLUNKER DEMO.

这篇关于如何在for循环中保证带有角度http rest api的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆